package com.uiui.zyappstore.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
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.uiui.zyappstore.R;
import com.uiui.zyappstore.base.BaseActivity;
import com.uiui.zyappstore.bean.AppInfo;
import com.uiui.zyappstore.bean.BaseResponse;
import com.uiui.zyappstore.bean.UserInfo;
import com.uiui.zyappstore.fragment.FeaturedFragment;
import com.uiui.zyappstore.network.NetInterfaceManager;
import com.uiui.zyappstore.service.GuardService;
import com.uiui.zyappstore.service.DownloadService;
import com.uiui.zyappstore.service.StepService;
import com.uiui.zyappstore.service.main.MainService;
import com.uiui.zyappstore.utils.JGYUtils;
import com.uiui.zyappstore.utils.SPUtils;
import com.uiui.zyappstore.utils.ToastUtil;
import com.uiui.zyappstore.utils.Utils;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


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");
        startService(new Intent(MainActivity.this, DownloadService.class));
        starService();
        JGYUtils.getInstance().checkLocalExternalFiles();
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_main;
    }

    @Override
    protected 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
    protected void initData() {
//        getAllAppPackageName();
    }

    private void starService() {
        startService(new Intent(this, GuardService.class));
        startService(new Intent(this, StepService.class));
        startService(new Intent(this, MainService.class));
        startService(new Intent(this, DownloadService.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();
//        getUserInfo();
    }

    @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");
    }

    @Override
    protected void setListener() {

    }

    private String[] permission = new String[]{
//            Permission.SYSTEM_ALERT_WINDOW,
//            Permission.CAMERA,
//            Permission.READ_SMS,
//            Permission.RECEIVE_SMS,
//            Permission.SEND_SMS,
            Permission.REQUEST_INSTALL_PACKAGES,
            Permission.READ_EXTERNAL_STORAGE,
            Permission.WRITE_EXTERNAL_STORAGE,
//            Permission.READ_PHONE_STATE
    };

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

    private void getUserInfo() {
        NetInterfaceManager.getInstance().getuserInfoControl().getUserinfo(Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<UserInfo>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResponse<UserInfo> userInfoBaseResponse) {
                        int code = userInfoBaseResponse.code;
                        //已经绑定
                        if (code == 200) {
                            UserInfo info = userInfoBaseResponse.data;
                            SPUtils.put(MainActivity.this, "isLogined", 1);
                            SPUtils.put(MainActivity.this, "admin_id", info.getAdmin_id());
                            SPUtils.put(MainActivity.this, "sn_id", info.getId());
                            if (!TextUtils.isEmpty(info.getGrade())) {
                                SPUtils.put(MainActivity.this, "sn_grade", info.getGrade());
                            }
                        }
                        //没有绑定
                        else if (code == 300) {
                            SPUtils.put(MainActivity.this, "isLogined", 0);
//                            Intent intent = new Intent();
//                            intent.putExtra("text", getResources().getString(R.string.no_bind));
//                            intent.setClass(MainActivity.this, HintActivity.class);
//                            startActivity(intent);
                        }
                        //没有设备
                        else if (code == 400) {
                            SPUtils.put(MainActivity.this, "isLogined", 2);

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getAllAppPackageName() {
        NetInterfaceManager.getInstance()
                .getQueryAllAppObservable()
                .subscribe(new Observer<BaseResponse<List<AppInfo>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResponse<List<AppInfo>> listBaseResponse) {
                        int code = listBaseResponse.code;
                        if (code == 200) {
                            List<AppInfo> infos = listBaseResponse.data;
                            String s = "";
                            for (AppInfo info : infos) {
                                s += info.getApp_package() + ",";
                            }
                            if (s.endsWith(",")) {
                                s = s.substring(0, s.length() - 1);
                            }
                            String qch_app_forbid_before = Settings.System.getString(getContentResolver(), "aole_app_forbid");
                            Log.e("getAllAppPackageName:", "qch_app_forbid_before" + qch_app_forbid_before);
//                            boolean aole_app_forbid = Settings.System.putString(getContentResolver(), "aole_app_forbid", s);
//                            Log.e("getAllAppPackageName", "aole_app_forbid:" + aole_app_forbid + ":" + s);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
