package com.yutou.jianr_mg.services;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.ExcelUtils;
import com.yutou.jianr_mg.Tools.Utils;
import com.yutou.jianr_mg.views.ExcelActivity;
import com.yutou.jianr_mg.views.WarView;

import org.json.JSONObject;

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

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

public class WindowsService extends Service {
    private MyBinder binder = new MyBinder();
    private Handler handler;
    private LinearLayout buttons, contextLayout;
    private FrameLayout side;
    private ImageView push, state;
    private WindowManager windowManager;
    private WindowManager.LayoutParams params;
    private ConstraintLayout mainLayout;
    private WebView webView;
    private ExcelUtils excel;
    private File excelFile;
    private Context context;
    private boolean input_flag = false,saveData=false;
    private String dataType,dataName;
    private WarView warView;

    private class MyBinder extends Binder {
        public WindowsService getService() {
            return WindowsService.this;
        }


    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            saveData = intent.getBooleanExtra("saveData", false);
            dataName=intent.getStringExtra("dataName");
            dataType=intent.getStringExtra("dataType");
            System.out.println("接收到配置，开关 = "+saveData+" name = "+dataName+" type = "+dataType);

        }
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("触发悬浮窗");
        context = WindowsService.this;
        handler = new Handler();
        warView=new WarView(context,null,webW,handler);
        try {
            SharedPreferences sp = getSharedPreferences(ExcelActivity.excelName, MODE_PRIVATE);
            excelFile = new File(sp.getString("default", "null.xlsx"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            initWindows();

        } catch (Exception e) {
            e.printStackTrace();
            stopSelf();
            Utils.toast(getApplicationContext(), "需要开启悬浮窗权限");
            Intent windowIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            windowIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
            startActivity(windowIntent);
            return;
        }
        initViews();
        serviceTimer();
        reloadUi();
    }

    private Timer timer;

    private void serviceTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            boolean isRuntime = false;
            boolean listener=true;
            @Override
            public void run() {
                MagicBoxService boxService = MagicBoxService.init();
                if (boxService == null) {
                    Utils.toast(context, "未安装专用客户端，部分功能将无法使用");
                    cancel();
                    return;
                }else{
                    boxService.setSaveData(saveData,dataName,dataType);
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("action", "getVersion");
                    boxService.setOrder(json, data -> {
                        boxService.clearOrder();
                        isRuntime = true;
                    });
                    if(listener) {
                        listener=false;
                        boxService.setOnListener(data -> {
                            try{
                                JSONObject jdata=new JSONObject(data);
                               //保留，还不知道干啥用
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        });
                    }
                    handler.post(() -> {
                        if (isRuntime) {
                            state.setImageResource(R.drawable.item_suspend_yuan_green);
                            state.setTag(true);
                        } else {
                            state.setImageResource(R.drawable.item_suspend_yuan_rad);
                            state.setTag(false);
                        }
                        isRuntime = false;
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1000);
    }

    private void initWindows() {
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        params.format = PixelFormat.RGBA_8888;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.gravity = Gravity.START | Gravity.TOP;
        params.alpha = 50;
        mainLayout = (ConstraintLayout) LayoutInflater.from(context).inflate(R.layout.activity_suspend, null);
        windowManager.addView(mainLayout, params);
    }

    private void initViews() {
        buttons = mainLayout.findViewById(R.id.buttons);
        state = mainLayout.findViewById(R.id.state);
        push = mainLayout.findViewById(R.id.push);
        side = mainLayout.findViewById(R.id.side);
        contextLayout = mainLayout.findViewById(R.id.contextLayout);
        webView = new WebView(context);
        contextLayout.addView(webView);
        initWebView();
        initWebUi();

        setWebUrl("http://www.baidu.com");
        state.setOnClickListener(view -> {
            if ((boolean) state.getTag()) {
                Utils.toast(context, "专用客户端已连接");
            } else {
                if (MagicBoxService.init() == null) {
                    Utils.toast(context, "专用客户端未安装(仅限共存版)");
                } else {
                    Utils.toast(context, "专用客户端未启动");
                   MagicBoxService service= MagicBoxService.init();
                   if(service!=null){
                       service.startService();
                   }
                }
            }
        });
        state.setTag(false);
        push.setTag(false);
        push.setOnClickListener(view -> {
            if ((boolean) push.getTag()) {
                push.setTag(false);
                side.setVisibility(View.VISIBLE);

            } else {
                push.setTag(true);
                side.setVisibility(View.GONE);
                webView.setVisibility(View.GONE);
            }
            reloadUi();
        });

        List<Button> buts = new ArrayList<>();
        buts.addAll(getMagicButtons());
        buts.addAll(getWebButtons());
        buts.addAll(getConfigButtons());

        for (Button button : buts) {
            buttons.addView(button);
        }

    }
    private int webW=0,webH=0;
    private void reloadUi() {
        if(webView.getLayoutParams().width>0) {
            webW = webView.getLayoutParams().width;
            webH = webView.getLayoutParams().height;
            contextLayout.getLayoutParams().width=webW;
        }
        int pushSize = Utils.getPixelsFromDp(AppData.activity, 10);
        int sideSize = Utils.getPixelsFromDp(AppData.activity, 45);
         int webSize =contextLayout.getLayoutParams().width;
        if (side.getVisibility() == View.GONE) {
            sideSize = 0;
        }
        if (contextLayout.getVisibility() == View.GONE) {
            webSize = 0;
        }
        if(webSize<0){

        }

        System.out.println("push size:" + pushSize);
        System.out.println("side size:" + sideSize);
        System.out.println("webs size:" + webSize);
        params.width =pushSize + sideSize +webSize;
        System.out.println("悬浮窗大小：" + params.width+" push="+pushSize+" side="+sideSize+" wr="+webSize+" wit="+Utils.getMetrics(AppData.activity).widthPixels);
        windowManager.updateViewLayout(mainLayout, params);
        initWebUi();
    }

    private void initWebUi() {
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        int width = -1;
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 横屏
            width = metrics.widthPixels;
            width = (int) (width - (width * 0.1));
            System.out.println("横屏");
        } else {
            // 竖屏
            width = metrics.widthPixels;
            width = (int) (width - (width * 0.2));
            System.out.println("竖屏");
        }
        webView.getLayoutParams().width = width;
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setAppCacheEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("加载网页：" + url);
                view.loadUrl(url);
                return true;
            }
        });
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    webView.goBack();

                }
                return false;
            }
        });
    }

    private List<Button> getWebButtons() {
        List<Button> list = new ArrayList<>();
        Button bbs = new Button(context);
        bbs.setText("论");
        bbs.setTag(200);
        bbs.setOnClickListener(new ButtonOnClick());

        Button address = new Button(context);
        address.setText("浏");
        address.setTag(201);
        address.setOnClickListener(new ButtonOnClick());

        Button bookmark = new Button(context);
        bookmark.setText("签");
        bookmark.setTag(202);
        bookmark.setOnClickListener(new ButtonOnClick());

        Button input = new Button(context);
        input.setText("输");
        input.setTag(203);
        input.setOnClickListener(new ButtonOnClick());

        Button strategy = new Button(context);
        strategy.setText("攻");
        strategy.setTag(204);
        strategy.setOnClickListener(new ButtonOnClick());

        list.add(bbs);
        list.add(strategy);
        list.add(address);
        list.add(input);
        //  list.add(bookmark);
        return list;
    }

    private List<Button> getMagicButtons() {
        List<Button> list = new ArrayList<>();
        if (MagicBoxService.init() != null||true) {
            Button map = new Button(context);
            Button user = new Button(context);
            Button pool = new Button(context);
            Button build = new Button(context);
            Button develop = new Button(context);
            Button expedition = new Button(context);
            Button fix = new Button(context);

            map.setText("图");
            user.setText("捞");
            pool.setText("战");
            build.setText("掉");
            develop.setText("开");
            expedition.setText("征");
            fix.setText("修");

            map.setTag(100);
            user.setTag(101);
            pool.setTag(102);
            build.setTag(103);
            develop.setTag(104);
            expedition.setTag(105);
            fix.setTag(106);

            map.setOnClickListener(new ButtonOnClick());
            user.setOnClickListener(new ButtonOnClick());
            pool.setOnClickListener(new ButtonOnClick());
            build.setOnClickListener(new ButtonOnClick());
            develop.setOnClickListener(new ButtonOnClick());
            expedition.setOnClickListener(new ButtonOnClick());
            fix.setOnClickListener(new ButtonOnClick());

            list.add(map);
            list.add(user);
            list.add(pool);
            list.add(build);
            //list.add(develop);
            //list.add(expedition);
            //list.add(fix);

        }
        return list;
    }

    private List<Button> getConfigButtons() {
        List<Button> list = new ArrayList<>();
        Button alpha = new Button(context);
        alpha.setText("透");
        alpha.setTag(300);
        alpha.setOnClickListener(new ButtonOnClick());

        Button exit = new Button(context);
        exit.setText("退");
        exit.setTag(301);
        exit.setOnClickListener(new ButtonOnClick());

        Button win = new Button(context);
        win.setText("拉");
        win.setTag(302);
        win.setOnClickListener(new ButtonOnClick());

        list.add(win);
        list.add(alpha);
        list.add(exit);
        return list;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        reloadUi();
    }
    private void setWebUrl(String url){
        handler.post(()->{
            if (contextLayout.getVisibility() == View.GONE) {
                contextLayout.setVisibility(View.VISIBLE);
            }
            if(excel!=null) {
                excel.close();
                excel = null;
            }
            if (webView.getVisibility() == View.GONE) {
                webView.setVisibility(View.VISIBLE);
                reloadUi();
            }
            setView(webView);
            reloadUi();
           webView.loadUrl(url);

        });
    }

    class ButtonOnClick implements View.OnClickListener {

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onClick(View view) {
            AlertDialog dialog;
            MagicBoxService service = MagicBoxService.init();
            JSONObject json;
            LinearLayout layout;
            try {

                switch ((int) view.getTag()) {
                    case 300:
                        try {
                            SeekBar bar = new SeekBar(context);
                            bar.setMin(1);
                            bar.setMax(230);
                            bar.setProgress((int) params.alpha);
                            bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                                    System.out.println("参数：" + i);
                                    params.alpha = i;
                                    windowManager.updateViewLayout(mainLayout, params);
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {

                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {

                                }
                            });
                            dialog = new AlertDialog.Builder(context)
                                    .setTitle("设置透明度")
                                    .setView(bar)
                                    .setPositiveButton("确定", (dialogInterface, i) -> dialogInterface.dismiss()).create();
                            dialog.getWindow().setType(params.type);
                            dialog.show();
                        }catch (Exception e){
                            e.printStackTrace();
                            Utils.toast(context,"可能您的设备不支持调节透明度");
                        }

                        break;
                    case 301:
                        timer.cancel();
                        webView.destroy();
                        contextLayout.removeAllViews();
                        mainLayout.removeAllViews();
                        windowManager.removeView(mainLayout);
                        if (excel != null) {
                            excel.stop();
                        }
                        if(warView!=null){
                            warView.close();
                        }
                        stopSelf();
                        break;
                    case 302:
                        Button button = (Button) view;
                        if (button.getText().toString().equals("拉")) {
                            button.setText("缩");
                            contextLayout.setVisibility(View.GONE);
                        } else {
                            button.setText("拉");
                            contextLayout.setVisibility(View.VISIBLE);
                        }
                        reloadUi();
                        break;
                    case 200:
                        if (contextLayout.getVisibility() == View.GONE) {
                            contextLayout.setVisibility(View.VISIBLE);
                        }

                        reloadUi();
                        setWebUrl("http://bbs.jianrmod.cn");
                        break;
                    case 201:
                        layout = new LinearLayout(context);
                        layout.setHorizontalGravity(LinearLayout.VERTICAL);
                        EditText webEdit = new EditText(context);
                        LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        webEdit.setLayoutParams(editParams);
                        webEdit.setText("http://");
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        layout.addView(webEdit);
                        layout.setLayoutParams(layoutParams);
                        dialog = new AlertDialog.Builder(context)
                                .setTitle("输入地址")
                                .setView(layout)
                                .setPositiveButton("跳转", (dialogInterface, i) -> {

                                    setWebUrl(webEdit.getText().toString());
                                    dialogInterface.dismiss();
                                })
                                .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
                                .create();
                        dialog.getWindow().setType(params.type);
                        dialog.show();
                    case 202:
                        break;
                    case 203:
                        if (input_flag) {
                            input_flag = false;
                            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
                            windowManager.updateViewLayout(mainLayout, params);
                            Utils.toast(context, "取消监听，网页不可输入内容，实体按键恢复");
                        } else {
                            input_flag = true;
                            params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
                            windowManager.updateViewLayout(mainLayout, params);
                            Utils.toast(context, "监听浏览器，网页可输入内容，实体按键失效");
                        }
                        break;
                    case 204:
                        if (!excelFile.exists()) {
                            Utils.toast(context, "离线资料不存在，请先下载离线资料");
                            return;
                        }

                        if(excel==null){
                            excel=new ExcelUtils(AppData.activity);
                           setView(excel.getReader());
                           excel.getReader().getLayoutParams().height=contextLayout.getLayoutParams().height;
                            excel.start(excelFile);
                        }
                        reloadUi();
                        break;

                    case 100:
                        if(service!=null){
                            json=service.getDealNode();
                            service.getGetWarResult();
                            if(json==null)
                                return;
                            JSONObject ext=new JSONObject(json.getString("ext"));
                            if(ext.getString("s").equals("pve")){
                                System.out.println("原参数："+ext.toString());
                                String url="http://js.ntwikis.com/jsp/apps/cancollezh/maps/detailnew.jsp?detailid="+((ext.getInt("n")/100)+"").replace("0","-");
                                System.out.println("url:"+url);
                                setWebUrl(url);
                            }
                            reloadUi();
                        }
                        break;
                    case 101:
                        if (service != null) {
                            json = service.getDealNode();
                            if(json==null)
                                return;
                            JSONObject ext=new JSONObject(json.getString("ext"));
                            System.out.println("EXT源："+ext.toString());
                            String url="http://www.jianrmod.cn/data/nodeDropInfo.html?node="+ext.getInt("n");
                            System.out.println("url:"+url);
                            setWebUrl(url);
                            reloadUi();
                        }
                        break;
                    case 102:
                        if(service!=null) {
                            setView(warView.initView());
                            warView.update(service,webW);
                        }
                        break;
                }

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

    private void setView(View view) {
        contextLayout.removeAllViews();
        contextLayout.addView(view);
    }
}
