package com.ycgis.macall.personalcenter.v.activity;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.viewpager2.widget.ViewPager2;

import com.anhui.police.market.callback.AbstractMarketResult;
import com.anhui.police.market.sdk.MarketConfigure;
import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.utils.DimensionConvert;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityMainBinding;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.presenter.BtnSkip;
import com.ycgis.macall.personalcenter.p.request.CommonCompositeManage;
import com.ycgis.macall.personalcenter.p.rxjava.ResultObserver;
import com.ycgis.macall.personalcenter.p.service.GetMessageService;
import com.ycgis.macall.personalcenter.util.InsertAppUtils;
import com.ycgis.macall.personalcenter.util.NotificationUtils;
import com.ycgis.macall.personalcenter.v.adapter.MainFragmentAdapter;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static android.app.Notification.EXTRA_CHANNEL_ID;
import static android.provider.Settings.EXTRA_APP_PACKAGE;

public class MainActivity extends BaseViewBindActivity<ActivityMainBinding> {
    private BtnSkip btnSkip;
    private int lastIndex = 0;

    @Override
    protected ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }

    @Override
    protected void init() {
//        LinearLayoutManager manager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
        viewBinding.mainPageView.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        customClickListener = new CustomClickListener(300) {
            @Override
            public void onSingleClick(View v) {
                bindViewClick(v);
            }
        };
        setViewOnClickListener(viewBinding.mainBtnBottom1);
        setViewOnClickListener(viewBinding.mainBtnBottom2);
        setViewOnClickListener(viewBinding.mainBtnBottom3);
        setViewOnClickListener(viewBinding.mainBtnBottom4);
        viewBinding.mainPageView.setOffscreenPageLimit(3);
        //TODO 设置是否可滑动切换
        // viewBinding.mainPageView.setUserInputEnabled(false);
        viewBinding.mainPageView.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                switchMainButton(viewBinding.mainPageView.getCurrentItem());
            }
        });
        btnSkip = new BtnSkip(getContext());
        btnSkip.setTextColor(R.color.bull,R.color.colorGrey5);
        btnSkip.add(0,btnSkip.new Content(viewBinding.mainTvBottom1,viewBinding.mainIvBottom1,R.drawable.icon_main_home,R.drawable.icon_main_home_def));
        btnSkip.add(1,btnSkip.new Content(viewBinding.mainTvBottom2,viewBinding.mainIvBottom2,R.drawable.icon_main_message,R.drawable.icon_main_message_def));
        btnSkip.add(2,btnSkip.new Content(viewBinding.mainTvBottom3,viewBinding.mainIvBottom3,R.drawable.icon_main_work,R.drawable.icon_main_work_def));
        btnSkip.add(3,btnSkip.new Content(viewBinding.mainTvBottom4,viewBinding.mainIvBottom4,R.drawable.icon_main_my,R.drawable.icon_main_my_def));
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.mainPageView.setAdapter(new MainFragmentAdapter(this));  //判断应用有无通知权限
        boolean bc = NotificationUtils.isNotifyEnabled(this);
        if (!bc) {
            //无权限时应弹框提醒
            showNotificationDialog();
        }
        startJobScheduler();
        //3.0.20240111 没有添加检测更新
        MarketConfigure.detectAppUpdates(this, false, "", new AbstractMarketResult() {
            @Override
            public void onResult(String result, boolean upgrade) {
                LogUtils.w(result);
            }

            @Override
            public void onConfirm(int stateType) {
                LogUtils.w("stateType:" + stateType);

            }

            @Override
            public void onCancel() {
                LogUtils.w("onCancel");
            }

            @Override
            public void onWarning() {
                LogUtils.w("onWarning");

            }

            @Override
            public void onResult(String result) {
                LogUtils.w(result);

            }
        });
//        installationDetectionComponents();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommonCompositeManage.getInstance().unDisposable("exitApp");
    }

//    //检测统一服务组件是否安装
//    private void installationDetectionComponents() {
//        if (new InsertAppUtils().isInspectStaticFaceSDK(getContext())) {
//            //没有安装统一服务组件
//            new AlertDialog.Builder(getContext())
//                    .setTitle(R.string.kind_reminder)
//                    .setCancelable(false)
//                    .setMessage(R.string.not_insert_usc_apk)
//                    .setNegativeButton("不安装", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    }).setPositiveButton("去下载", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                    Intent intent = new Intent(Intent.ACTION_VIEW);
//                    intent.setData(Uri.parse("http://20.90.1.135/download/tyfwzj.apk"));
//                    startActivity(intent);
//                }
//            }).create().show();
//        }
//    }

    @Override
    protected void bindViewClick(View v) {
        int num = 0;
        if (v.getId() == R.id.main_btn_bottom1) {
            num = 0;
        } else if (v.getId() == R.id.main_btn_bottom2) {
            num = 1;
        } else if (v.getId() == R.id.main_btn_bottom3) {
            num = 2;
        } else if (v.getId() == R.id.main_btn_bottom4) {
            num = 3;
        }
        viewBinding.mainPageView.setCurrentItem(num);
        switchMainButton(num);
    }

    private void showNotificationDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_remind, null, false);
        Dialog dialog = new AlertDialog.Builder(getContext(), R.style.MyDialogTheme)
                .setView(view)
                .setCancelable(false)
                .create();
        dialog.show();
        WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        layoutParams.width = dm.widthPixels - DimensionConvert.dip2px(getContext(), 50);
        layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        layoutParams.gravity = Gravity.CENTER;
        dialog.getWindow().setAttributes(layoutParams);
        dialog.findViewById(R.id.btn_determine).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                dialog.dismiss();
                setNotificationActivity();
            }
        });
    }

    public void setNotificationActivity() {
        Intent localIntent = new Intent();
        //直接跳转到应用通知设置的代码：
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0及以上
            localIntent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            localIntent.putExtra(EXTRA_APP_PACKAGE, getPackageName());
            localIntent.putExtra(EXTRA_CHANNEL_ID, getApplicationInfo().uid);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0以上到8.0以下
            //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
            localIntent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            localIntent.putExtra("app_package", getPackageName());
            localIntent.putExtra("app_uid", getApplicationInfo().uid);
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {//4.4
            localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            localIntent.addCategory(Intent.CATEGORY_DEFAULT);
            localIntent.setData(Uri.parse("package:" + getPackageName()));
        } else {
            //4.4以下没有从app跳转到应用通知设置页面的Action，可考虑跳转到应用详情页面,
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
            }
        }
        startActivityForResult(localIntent, 50);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 50 && resultCode == 0) {
            //判断应用有无通知权限
            boolean bc = NotificationUtils.isNotifyEnabled(this);
            if (!bc) {
                //无权限时应弹框提醒
                showNotificationDialog();
            }
        }
    }

    public void onSkipMyDetails(View view) {
        startActivity(new Intent(getContext(), MyDetailsActivity.class));
    }

    //核查个人中心对接新警综

    public void onJumpMessage(View view) {
        viewBinding.mainPageView.setCurrentItem(1);
        switchMainButton(1);
    }

    private void switchMainButton(int buttonNum) {
        btnSkip.unDateStatus(lastIndex,false);
        btnSkip.unDateStatus(buttonNum,true);
        lastIndex = buttonNum;
//        switch (buttonNum) {
//            case 0:
//                viewBinding.mainIvBottom1.setImageDrawable(getDrawables(R.drawable.icon_main_home));
//                viewBinding.mainIvBottom2.setImageDrawable(getDrawables(R.drawable.icon_main_message_def));
//                viewBinding.mainIvBottom3.setImageDrawable(getDrawables(R.drawable.icon_main_work_def));
//                viewBinding.mainIvBottom4.setImageDrawable(getDrawables(R.drawable.icon_main_my_def));
//                viewBinding.mainTvBottom1.setTextColor(getColors(R.color.blue));
//                viewBinding.mainTvBottom2.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom3.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom4.setTextColor(getColors(R.color.colorGrey5));
//                break;
//            case 1:
//                viewBinding.mainIvBottom1.setImageDrawable(getDrawables(R.drawable.icon_main_home_def));
//                viewBinding.mainIvBottom2.setImageDrawable(getDrawables(R.drawable.icon_main_message));
//                viewBinding.mainIvBottom3.setImageDrawable(getDrawables(R.drawable.icon_main_work_def));
//                viewBinding.mainIvBottom4.setImageDrawable(getDrawables(R.drawable.icon_main_my_def));
//                viewBinding.mainTvBottom1.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom2.setTextColor(getColors(R.color.blue));
//                viewBinding.mainTvBottom3.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom4.setTextColor(getColors(R.color.colorGrey5));
//                break;
//            case 2:
//                viewBinding.mainIvBottom1.setImageDrawable(getDrawables(R.drawable.icon_main_home_def));
//                viewBinding.mainIvBottom2.setImageDrawable(getDrawables(R.drawable.icon_main_message_def));
//                viewBinding.mainIvBottom3.setImageDrawable(getDrawables(R.drawable.icon_main_work));
//                viewBinding.mainIvBottom4.setImageDrawable(getDrawables(R.drawable.icon_main_my_def));
//                viewBinding.mainTvBottom1.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom2.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom3.setTextColor(getColors(R.color.blue));
//                viewBinding.mainTvBottom4.setTextColor(getColors(R.color.colorGrey5));
//                break;
//            case 3:
//                viewBinding.mainIvBottom1.setImageDrawable(getDrawables(R.drawable.icon_main_home_def));
//                viewBinding.mainIvBottom2.setImageDrawable(getDrawables(R.drawable.icon_main_message_def));
//                viewBinding.mainIvBottom3.setImageDrawable(getDrawables(R.drawable.icon_main_work_def));
//                viewBinding.mainIvBottom4.setImageDrawable(getDrawables(R.drawable.icon_main_my));
//                viewBinding.mainTvBottom1.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom2.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom3.setTextColor(getColors(R.color.colorGrey5));
//                viewBinding.mainTvBottom4.setTextColor(getColors(R.color.blue));
//                break;
//        }
    }

    private boolean isExit = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                finish();
                return false;
            } else {
                isExit = true;
                ToastUtil.centered(getContext(), "在按一次退出个人中心");
                modificationTime();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @SuppressLint("NewApi")
    public void startJobScheduler() {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        @SuppressLint("JobSchedulerService") JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(this, GetMessageService.class));
        if (Build.VERSION.SDK_INT >= 24) {
            builder.setMinimumLatency(RuanseeApplication.RefreshMessageTime); //执行的最小延迟时间
            builder.setOverrideDeadline(RuanseeApplication.RefreshMessageTime);  //执行的最长延时时间
            builder.setBackoffCriteria(RuanseeApplication.RefreshMessageTime, JobInfo.BACKOFF_POLICY_LINEAR);//线性重试方案
        } else {
            builder.setPeriodic(RuanseeApplication.RefreshMessageTime);
        }
        builder.setPersisted(true);  // 设置设备重启时，执行该任务
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setRequiresCharging(false);//设置是否在只有插入充电器的时候执行
        builder.setRequiresDeviceIdle(false);//设置手机系统处于空闲状态下执行
        JobInfo info = builder.build();
        jobScheduler.schedule(info); //开始定时执行该系统任务
    }

    private void modificationTime() {
        Observable.timer(1000, TimeUnit.MILLISECONDS)
                .subscribe(new ResultObserver<Long>("exitApp") {
                    @Override
                    protected void onSubscribe(String identifierKey, @NotNull Disposable d) {
                        CommonCompositeManage.getInstance().addDisposable(identifierKey,d);
                    }

                    @Override
                    protected void onNext(String identifierKey, @NotNull Long data) {
                        CommonCompositeManage.getInstance().unDisposable(identifierKey);
                        isExit = false;
                    }

                    @Override
                    protected void onComplete(String identifierKey) {
                        CommonCompositeManage.getInstance().unDisposable(identifierKey);
                        isExit = false;
                    }
                });
    }
}