package com.rdiot.yx485.main;

import static com.rdiot.yx485.UpdateMgr.GET_UNKNOWN_APP_SOURCES;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.navigation.NavigationBarView;
import com.igexin.sdk.PushManager;
import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.R;
import com.rdiot.yx485.UpdateBean;
import com.rdiot.yx485.UpdateMgr;
import com.rdiot.yx485.UpdateRequestBean;
import com.rdiot.yx485.adapter.MainHomePagerAdapter;
import com.rdiot.yx485.bean.HomeBase;
import com.rdiot.yx485.databinding.ActivityMainTabBinding;
import com.rdiot.yx485.fragment.DiscoverFragment;
import com.rdiot.yx485.fragment.PersonFragment;
import com.rdiot.yx485.fragment.SceneFragment;
import com.rdiot.yx485.fragment.TopFragment;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.util.IntentUtils;
import com.rdiot.yx485.widget.CommonPopupWindow;
import com.zcolin.frame.http.ZHttp;
import com.zcolin.frame.http.response.ZResponse;
import com.zcolin.frame.util.DisplayUtil;
import com.zcolin.frame.util.FileUtil;
import com.zcolin.frame.util.SpUtil;

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

import okhttp3.Response;

public class MainActivityTab extends BaseActivity implements NavigationBarView.OnItemSelectedListener {
    private final List<Fragment> fragments = new ArrayList<>();
    private final List<Integer> mNavIds = new ArrayList<>();
    private ActivityMainTabBinding mBinding;
    private String updataurl, updateData;
    private MainViewModel mViewModel;
    private CommonPopupWindow homeListPopupWindow;
    private List<HomeBase> homeList;

    public static void newIntent(Context context, boolean fromLogin) {
        Intent intent = new Intent(context, MainActivityTab.class);
        intent.putExtra("fromLogin", fromLogin);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainTabBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        initData();
        setupViewpager();
        //  checkupdate();
        checkFirstLogin();
    }

    private void initData() {
        PushManager.getInstance().initialize(this);
        mViewModel = new ViewModelProvider(this).get(MainViewModel.class);
        mViewModel.getErrorMessage().observe(this, this::showMessage);

        mViewModel.getHomeList().observe(this, data -> homeList = data);
        mViewModel.getInitResult().observe(this, success -> {
            LogUtils.d(success ? "初始化成功" : "初始化失败");
        });
        mViewModel.refreshToken();
    }

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

    private void initAPP() {
        boolean fromLogin = getIntent().getBooleanExtra("fromLogin", false);
        String clientid = PushManager.getInstance().getClientid(this);
        System.out.println(String.format("clientid:%s", clientid));

        if (TextUtils.isEmpty(clientid)) {
            new Handler().postDelayed(this::initAPP, 1000);
            return;
        }

        @SuppressLint("HardwareIds")
        String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        System.out.println(String.format("androidId:%s", androidId));
        mViewModel.initializeApp(androidId, clientid, fromLogin ? 2 : 1);
    }

    private void setupViewpager() {
        mNavIds.clear();
        mNavIds.add(R.id.navigation_home);
        mNavIds.add(R.id.navigation_scene);
        mNavIds.add(R.id.navigation_discover);
        mNavIds.add(R.id.navigation_mine);

        fragments.clear();
        fragments.add(TopFragment.newInstance("", ""));
        fragments.add(SceneFragment.newInstance("", ""));
        fragments.add(DiscoverFragment.newInstance());
        fragments.add(PersonFragment.newInstance());
        MainHomePagerAdapter adapter = new MainHomePagerAdapter(this, fragments);
        mBinding.pager.setAdapter(adapter);
        mBinding.pager.setUserInputEnabled(false);
        mBinding.pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position < mNavIds.size()) {
                    mBinding.bottomNav.setSelectedItemId(mNavIds.get(position));
                }
            }
        });
        mBinding.bottomNav.setOnItemSelectedListener(this);
    }

    /**
     * 更新弹窗
     */
    private void update(String content, String dwurl) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder
                .setTitle("系统更新")
                .setMessage(content)
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String url = MainActivityTab.this.getFilesDir() + "/wuheng.apk";
                        File file = new File(url);
                        FileUtil.delete(file);
                        UpdateMgr.checkPermission(MainActivityTab.this, dwurl);
                    }
                })
                .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        alertDialog.show();
    }

    private void checkupdate() {
        long appVersionCode = 1;
        String appVersionName = "1.0.0";
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = packageInfo.getLongVersionCode();
            } else {
                appVersionCode = (long) packageInfo.versionCode;
            }
            appVersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // Log.e("", e.getMessage());
        }
        String type = SpUtil.getString("token_type", "");
        String token = SpUtil.getString("access_token", "");
        String key = type + " " + token;
        LinkedHashMap<String, String> headerParams = new LinkedHashMap<>();
        headerParams.put("Authorization", key);
        UpdateRequestBean bean = new UpdateRequestBean();
        bean.version = appVersionName;
        bean.platform = "ANDROID";
        ZHttp.postWithHeader(Url.CHECKVERSION,
                (LinkedHashMap<String, String>) headerParams, bean, new ZResponse<UpdateBean>() {
                    @Override
                    public void onSuccess(Response response, UpdateBean resObj) {
                        if (resObj != null && resObj.data != null) {
                            if (resObj.data.need_update) {
                                if (resObj.data.update_info != null) {
                                    updataurl = resObj.data.update_info.download_url;
                                    if (resObj.data.update_info.content != null) {
                                        updateData = resObj.data.update_info.content;
                                        update(resObj.data.update_info.content, updataurl);
                                    } else {
                                        update("版本有更新", updataurl);
                                    }
                                    if (resObj.data.update_info.force_update) {
                                        //  updatedialogPopupWindow.setCancelBtnText("退出");
                                    }
                                }
                            } else {
                                // Toast.makeText(MainActivityTab.this, resObj.message, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onError(int code, String error) {
                        super.onError(code, error);
                        Toast.makeText(MainActivityTab.this, error, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == GET_UNKNOWN_APP_SOURCES) {
            Toast.makeText(this, "安装应用", Toast.LENGTH_SHORT).show();
            update(updateData, updataurl);
        }
    }

    // 请求相机权限
    private void requestCameraPermission() {
        // 检查是否已经拥有权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    100);
        }
    }

    // 处理权限请求的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予
            } else {
                // 权限被拒绝
                Toast.makeText(this, "相机权限被拒绝，无法使用相机功能", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int index = mNavIds.indexOf(item.getItemId());
        if (index >= 0 && index < fragments.size()) {
            mBinding.pager.setCurrentItem(index);
            return true;
        }
        return false;
    }

    private void checkFirstLogin() {
        boolean isFirstLogin = SpUtil.getBoolean("app_first_login", false);
        if (isFirstLogin) {
            IntentUtils.intentToSetPwd(this, true);
        }
    }

    public void showHomeListWindow(TextView view) {
        if (homeList == null || homeList.isEmpty()) {
            showMessage("当前家庭列表数据为空");
            return;
        }

        if (homeListPopupWindow == null) {
            homeListPopupWindow = new CommonPopupWindow(this);
            for (HomeBase home : homeList) {
                homeListPopupWindow.addMenuItem(home.getName(), v1 -> {
                    mViewModel.updateDefaultHome(home);
                });
            }
        }
        homeListPopupWindow.show(view, 0, DisplayUtil.dip2px(this, 8));
    }

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

    @Override
    protected void onDestroy() {
        if (homeListPopupWindow != null) {
            homeListPopupWindow.dismiss();
            homeListPopupWindow = null;
        }
        super.onDestroy();
    }
}