package com.beanpodtech.allinone.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.aliyun.player.alivcplayerexpand.util.database.DatabaseHelper;
import com.aliyun.player.alivcplayerexpand.util.database.DatabaseManager;
import com.aliyun.player.alivcplayerexpand.util.database.LongVideoDatabaseManager;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.bean.Carousel;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.BoxUtil;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.NetWorkUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;
import cn.eeo.common.util.StringUtil;
import okhttp3.RequestBody;

public class StartpageActivity extends Activity {
    private static final String TAG = "StartpageActivity";
    private int[] images = new int[]{R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four};
    private RequestOptions requestOptions;
    private BGABanner banner;
    private ImageView ivTemp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideStatusBar();
        setContentView(R.layout.activity_startpage);

        requestOptions = new RequestOptions()
                .placeholder(R.drawable.one)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);

        banner = findViewById(R.id.banner);
        ivTemp = findViewById(R.id.iv_temp);
        ivTemp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StartpageActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        });
        banner.setDelegate(new BGABanner.Delegate() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, @Nullable Object model, int position) {
                Intent intent = new Intent(StartpageActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        });
        requestPower();

        if (StringUtil.isEmpty(SpUtil.getInstace().getString(Contants.USER_ID, ""))) {
            startActivity(new Intent(this, LoginActivity.class));
        } else {
            startActivity(new Intent(this, HomeActivity.class));
        }
        finish();
    }

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

    HashMap<String, String> map = new HashMap<>();
    List<Carousel.ListBean.UrlBean> list;

    public void carousel() {

        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        final RequestBody body = HttpUtils.getRequestJson(map);
        OkGoBuilder.getInstance().url(UrlConfig.HOMECAROUSEL).method(OkGoBuilder.PSOT).cls(Carousel.class).Builder(StartpageActivity.this).requestBody(body).callback(new OkGoUtil<Carousel>(Carousel.class) {
            @Override
            public void onSuccess(Response<Carousel> response1) {
                Log.d(TAG, "onSuccess: " + response1.code());
                if (response1.body() instanceof Carousel) {
                    Carousel body1 = response1.body();
                    if (body1 != null) {
                        String json = new Gson().toJson(body1);
                        SpUtil.getInstace().save(Contants.CAROUSEL_LIST, json);
                        Carousel.ListBean a = body1.getList();
                        if (a != null) {
                            list = body1.getList().getUrl();
                        }


                        // ======== 轮播 有数据  才显示轮播图  =======
                        if (list != null && list.size() > 0) {

                            banner.setVisibility(View.VISIBLE);
                            ivTemp.setVisibility(View.GONE);

                            List<String> listUrl = new ArrayList<>();
                            List<Integer> listDelayTime = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                listUrl.add(list.get(i).getCarouselUrl());
                                listDelayTime.add(list.get(i).getTime());
                            }
                            if (listDelayTime.size() != 0) {
                                banner.setAutoPlayInterval(listDelayTime.get(0));
                            }

                            banner.setPageChangeDuration(2000);
                            banner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                                @Override
                                public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                                    itemView.setScaleType(ImageView.ScaleType.FIT_XY);
                                    Glide.with(StartpageActivity.this).load(model).apply(requestOptions).into(itemView);
                                }
                            });
                            banner.setData(listUrl, null);

                            banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                                Log.i("TAG", "=====onPageScrolled=" + position);
                                }

                                @Override
                                public void onPageSelected(int position) {
//                                Log.i("TAG", "=====onPageSelected=" + position);
                                    banner.setAutoPlayInterval(listDelayTime.get(position));

                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                            });

                            return;
                        }

                    }

                }
                banner.setVisibility(View.GONE);
                ivTemp.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(Response<Carousel> response) {
                super.onError(response);
                Log.d(TAG, "onError: " + response.code());
                banner.setVisibility(View.GONE);
                ivTemp.setVisibility(View.VISIBLE);
            }
        }).build();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (NetWorkUtils.isNetworkConnected(this)) {
//            carousel();
//            banner.setVisibility(View.VISIBLE);
//            ivTemp.setVisibility(View.GONE);
//        } else {
//            banner.setVisibility(View.GONE);
//            ivTemp.setVisibility(View.VISIBLE);
//        }
        BoxUtil.hideBottomUIMenu(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void requestPower() {
        //判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.ADD_VOICEMAIL)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.USE_SIP)
                != PackageManager.PERMISSION_GRANTED) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CALL_PHONE) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.RECORD_AUDIO) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_PHONE_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_CALL_LOG) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_CALL_LOG) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ADD_VOICEMAIL) || ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.USE_SIP)) {//这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false

            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG, Manifest.permission.ADD_VOICEMAIL, Manifest.permission.USE_SIP}, 1);
            }
        } else {
            DatabaseManager.getInstance().createDataBase(this, DatabaseHelper.getDB_PATH(this));
            LongVideoDatabaseManager.getInstance().createDataBase(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DatabaseManager.getInstance().createDataBase(this, DatabaseHelper.getDB_PATH(this));
        LongVideoDatabaseManager.getInstance().createDataBase(this);
    }

    //全屏并且隐藏状态栏
    private void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }
}
