package com.yutou.jianr_mg;


import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;
import com.umeng.analytics.MobclickAgent;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.MAdConfig;
import com.yutou.jianr_mg.Data.MGamePackname;
import com.yutou.jianr_mg.Data.SConfig;
import com.yutou.jianr_mg.Data.UUserdata;
import com.yutou.jianr_mg.Data.User;
import com.yutou.jianr_mg.Databases.UserDatabase;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.Tools.ActivitysManager;
import com.yutou.jianr_mg.Tools.AdTools;
import com.yutou.jianr_mg.Tools.AppPermissions;
import com.yutou.jianr_mg.Tools.ConfigUtils;
import com.yutou.jianr_mg.Tools.JianRUtils;
import com.yutou.jianr_mg.Tools.Log;
import com.yutou.jianr_mg.Tools.Utils;
import com.yutou.jianr_mg.views.MapView;
import com.yutou.jianr_mg.views.RegisterActivity;
import com.yutou.jianr_mg.views.WebActivity;

import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.InputStream;

import me.drakeet.materialdialog.MaterialDialog;

/**
 * Created by 58381 on 2018/1/18.
 */

public class LoadingActivity extends AppCompatActivity {
  //  private static final String APPID = "1105310947";
  //  private static final String POSID = "7090537892072921";
    public static String url = null;

    private LinearLayout loginLayout, adLayout;
    private Button login, reg;
    private TextView notlogin, uname, password;
    private ImageView icon;
    private Handler handler;
    private boolean isLogin = false;
    private Class clazz;
    private MAdConfig ad=new MAdConfig();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppData.debug=true;
        System.out.println("update");
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //setContentView(R.layout.activity_loading);
        Utils.setImmersion(this);
        if (url == null) {
            clazz = MainActivity.class;
        } else {
            clazz = WebActivity.class;
        }
        handler = new Handler();
       /* initViews();
        initData();
        initAd();*/
        JianRUtils.reloadShipType();
        MapView mapView=new MapView(this);
        setContentView(mapView.getView());
    }

    private void login(String name, String pass) {
        try {
            JSONObject json = new JSONObject();
            json.put("uname", name);
            json.put("pass", pass);
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.USER_LOGIN, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        final String msg = json.getString("msg");
                        if (json.getInt("code") == 100) {
                            AppData.user = JSON.parseObject(json.getJSONObject("data").toString(), User.class);
                            AppData.Token = json.getString("token");
                            AppData.user.setToken(AppData.Token);
                            UserDatabase.init().login(AppData.user.getId(), AppData.user.getName(), AppData.Token);
                            isLogin = true;
                            handler.post(() -> start());
                        } else {
                            handler.post(() -> Utils.toast(LoadingActivity.this, msg));
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void httpError(Exception e) {
                    e.printStackTrace();
                    Utils.toast(LoadingActivity.this, "登录失败：" + e.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initData() {
        AssetManager manager = getResources().getAssets();
        try {
            String fileName;
            switch (Build.CPU_ABI) {
                case "armeabi-v7a":
                    fileName = "busybox-armv7l";
                    break;
                default:
                    fileName = "busybox-armv7l";
            }
            InputStream inputStream = manager.open(fileName);
            //jar.createNewFile();
            FileOutputStream outputStream = new FileOutputStream(getFilesDir() + "/busybox");
            int len = 0;
            byte[] bytes = new byte[inputStream.available()];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  Utils.toast(this, Build.CPU_ABI);
        initUser();
        initGamePackName();
        initConfig();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            ready(1);
        } else
            ActivityCompat.requestPermissions(this, AppPermissions.permissions, AppPermissions.REQUEST_CODE);
    }

    private void initConfig() {
        try {
            HttpUtils.get(HttpApi.HOME_URL + HttpApi.MG_CONFIG, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        if (json != null && json.getInt("code") == 100) {
                            AppData.appConfig = JSON.parseObject(json.getJSONObject("data").toString(), SConfig.class);
                        }
                        ready(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {
                    e.printStackTrace();
                    Utils.toast(LoadingActivity.this, "初始化失败:" + e.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initGamePackName() {
        try {
            HttpUtils.get(HttpApi.HOME_URL + HttpApi.MOD_GAME_PACKNAME, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        Log.i(HttpApi.MOD_GAME_PACKNAME, string);
                        JSONObject json = new JSONObject(string);
                        AppData.packnames = JSON.parseArray(json.getJSONArray("data").toString(), MGamePackname.class);
                        ready(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initUser() {
        try {
            JSONObject json = new JSONObject();
            json.put("token", AppData.Token);
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.USER_TEST, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        final String msg = json.getString("msg");
                        Log.i("LOGIN", "登录状态：" + string);
                        if (json.getInt("code") == 100) {
                            JSONObject data = json.getJSONObject("data").getJSONObject("data");
                            AppData.user = JSON.parseObject(data.getJSONObject("user").toString(), User.class);
                            AppData.userdata = JSON.parseObject(data.getJSONObject("userdata").toString(), UUserdata.class);
                            ConfigUtils.init().save(ConfigUtils.collection, data.getJSONArray("collection"));
                            isLogin = true;
                        } else {
                            handler.post(() -> Utils.toast(LoadingActivity.this, msg));
                            isLogin = false;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            start();
        }

    }
    private void initAd(){
        try {
            JSONObject json = new JSONObject();
            json.put("type", 1);
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.AD_GET, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        if (json.getInt("code") == 100) {
                            ad = JSON.parseObject(json.getJSONObject("data").toString(), MAdConfig.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    AppData.handler.post(()->startOpenAd());
                }

                @Override
                public void httpError(Exception e) {
                    handler.post(()->start());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            start();
        }
    }
    private void initViews() {
        loginLayout = findViewById(R.id.loginLayout);
        login = findViewById(R.id.login);
        notlogin = findViewById(R.id.notlogin);
        icon = findViewById(R.id.icon);
        uname = findViewById(R.id.uname);
        password = findViewById(R.id.password);
        adLayout = findViewById(R.id.adLayout);
        reg = findViewById(R.id.reg);


        Intent regIntent = getIntent();
        if (regIntent != null) {
            String name = regIntent.getStringExtra("name");
            String pass = regIntent.getStringExtra("password");
            if (!Utils.testStringIsNull(name, pass)) {
                uname.setText(name);
                password.setText(pass);
                login.callOnClick();
            }
        }

        notlogin.setOnClickListener(view -> start());
        login.setOnClickListener(view -> {
            String name = uname.getText().toString();
            String pass = password.getText().toString();
            if (Utils.testStringIsNull(name, pass)) {
                Utils.toast(LoadingActivity.this, "账号/密码 不能为空");
                return;
            }
            login(name, pass);
        });
        reg.setOnClickListener(view -> {
            Intent intent = new Intent(LoadingActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    public void start() {
        adLayout.removeAllViews();
        adLayout.setVisibility(View.GONE);
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.topMargin = Utils.getPixelsFromDp(this, 512);
        params.startToStart = Utils.getPixelsFromDp(this, 8);
        params.startToEnd = Utils.getPixelsFromDp(this, 8);
        // icon.setLayoutParams(params);
        if (true) {
            // return;
        }

        PackageManager manager = getPackageManager();
        String code = "";
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            code = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (AppData.appConfig != null && !AppData.appConfig.getApkVersion().equals(code)) {
            MaterialDialog dialog = new MaterialDialog(this);
            dialog.setTitle("检测到更新");
            dialog.setMessage(AppData.appConfig.getMessage());
            dialog.setNegativeButton("放弃", v -> {
                dialog.dismiss();
                if (isLogin) {
                    Intent intent = new Intent(LoadingActivity.this, clazz);
                    if (url != null) {
                        intent.putExtra("url", url);
                    }
                    startActivity(intent);
                   finish();
                } else {
                    Utils.toast(this, "未登录/登录信息失效");
                    showLogin();
                }
            });
            dialog.setPositiveButton("升级", v -> {
                dialog.dismiss();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(AppData.appConfig.getApkUrl()));
                startActivity(intent);
                ActivitysManager.AppExit(this);
            });
            dialog.show();

        } else {
            if (isLogin) {
                Intent intent = new Intent(LoadingActivity.this, clazz);
                if (url != null) {
                    intent.putExtra("url", url);
                }
                startActivity(intent);
                finish();
            } else {
                Utils.toast(this, "未登录/登录信息失效");
                showLogin();
            }
        }

    }

    private void showLogin() {
        Animation iconAnim = AnimationUtils.loadAnimation(this, R.anim.loading_icon);
        Animation loginAnim = AnimationUtils.loadAnimation(this, R.anim.loading_login);
        iconAnim.setAnimationListener(new MyAnimListener());
        loginAnim.setAnimationListener(new MyAnimListener());
        icon.startAnimation(iconAnim);
        loginLayout.setAlpha(0f);
        loginLayout.setVisibility(View.VISIBLE);
        loginLayout.startAnimation(loginAnim);

    }

    private class MyAnimListener implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            loginLayout.setAlpha(1f);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    }

    private int readys = 0;

    private synchronized void ready(int i) {
        readys += i;
        Log.i(readys + "");
        if (readys == 4) {
            handler.postDelayed(() -> {


            }, 0);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean flag = true;
        if (requestCode == AppPermissions.REQUEST_CODE) {
            for (String permission : AppPermissions.permissions) {
                if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    System.out.println(permission);
                    flag = false;
                    break;
                }
            }
            if (!flag) {
                MaterialDialog dialog = new MaterialDialog(this);
                dialog.setTitle(">__<");
                dialog.setMessage("缺少起床的必要权限哦！");
                dialog.setNegativeButton("不给", view -> {
                    Utils.toast(LoadingActivity.this, "哼，小气(可能会发生意外闪退问题）");
                   /* handler.postDelayed(() -> {
                        ActivitysManager.AppExit(LoadingActivity.this);
                        dialog.dismiss();
                    }, 300);*/
                   dialog.dismiss();
                    ready(1);
                });
                dialog.setPositiveButton("拿去吧", view -> {
                    ActivityCompat.requestPermissions(LoadingActivity.this, AppPermissions.permissions, AppPermissions.REQUEST_CODE);
                    dialog.dismiss();
                });
                dialog.show();
            } else {
                Utils.isPermissions=true;
                ready(1);
            }
        }
    }

    private void startOpenAd() {
        if(ad.getAdshow()!=1){
            start();
            return;
        }
        AdTools.upload(AdTools.Open,AdTools.req);
       SplashAD splashAD= new SplashAD(this, ad.getAppid(), ad.getPosid(), new SplashADListener() {
            @Override
            public void onADDismissed() {
                start();
            }

            @Override
            public void onNoAD(AdError adError) {
                handler.postDelayed(() -> start(), 3000);
            }

            @Override
            public void onADPresent() {

            }

            @Override
            public void onADClicked() {
                AdTools.upload(AdTools.Open,AdTools.click);
            }

            @Override
            public void onADTick(long l) {

            }

            @Override
            public void onADExposure() {
                AdTools.upload(AdTools.Open,AdTools.show);
            }
        });
        splashAD.fetchAndShowIn(adLayout);

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

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