package com.yutou.jianr_mg.views;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AppCompatActivity;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Interfaces.DownloadFileInerface;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.ExcelUtils;
import com.yutou.jianr_mg.Tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import me.drakeet.materialdialog.MaterialDialog;

public class ExcelActivity extends AppCompatActivity {

    private ExcelUtils excel;
    private JSONObject parame;
    private KProgressHUD hud;
    public static String excelName="excelData";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_excel);
        Intent intent = getIntent();

        hud = Utils.showLoading(this, "请稍后", "文件正在下载中");
        if (intent != null) {
            String parameter = intent.getStringExtra("parameter");
            if (parameter != null) {
                try {
                    parame = new JSONObject(parameter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                finish();
            }
        } else {
            finish();
        }

        excel = new ExcelUtils(this);
        ConstraintLayout layout = findViewById(R.id.layout);
        layout.addView(excel.getReader(), ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT);
        initData();
        SharedPreferences preferences=getSharedPreferences("config", Context.MODE_PRIVATE);
        if(Build.VERSION.SDK_INT>=29&&!preferences.getBoolean("exceldialog",false)){
            MaterialDialog dialog=new MaterialDialog(this);
            dialog.setTitle("看不到攻略？");
            dialog.setMessage("如果本页面内容是空的，请前往 个人中心-设置-设置TBS内核-安装线上内核\n成功后手动重启下盒子应该就行了，如果还是没有请再试一次");
            dialog.setPositiveButton("已经正常", view -> {
                preferences.edit().putBoolean("exceldialog",true).apply();
                dialog.dismiss();
            });
            dialog.setNegativeButton("下次再说", view -> dialog.dismiss());
            dialog.show();
        }
    }
    SharedPreferences sp;
    private void initData() {
        try {
            sp=getSharedPreferences(excelName,MODE_PRIVATE);
            File path = new File(Utils.getAppPath() + "/data/");
            if (!path.exists()) {
                path.mkdirs();
                downlaodFile();
                return;
            }

            File file = new File(Utils.getAppPath() + "/data/" + parame.getString("fileName"));
            if (!file.exists()) {
                downlaodFile();

                return;
            }
            if(!sp.getString(parame.getString("name"),"").equals(parame.getString("fileVersion"))){
                downlaodFile();
                return;
            }
            initView();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void downlaodFile() {
        MaterialDialog dialog = new MaterialDialog(this);
        dialog.setTitle("资料缺失/过期");
        dialog.setMessage("检测到当前资料并不存在或需要更新，是否进行更新（建议在WIFI网络下进行)");
        dialog.setNegativeButton("取消", view -> {
            dialog.dismiss();
            finish();
        });
        dialog.setPositiveButton("确定", view -> {
            dialog.dismiss();
            hud.show();
            try {
                HttpUtils.downloadFile(parame.getString("url"), Utils.getAppPath() + "/data/", new DownloadFileInerface() {
                    String fileName;
                    @Override
                    public boolean downloading(String fileName, int current, long length) {
                        this.fileName=fileName;
                        AppData.handler.post(()->hud.setDetailsLabel("下载中 "+current+"/100"));
                        return true;
                    }

                    @Override
                    public void over(boolean isOver) {
                        if(!isOver){
                            hud.dismiss();
                            Utils.toast(ExcelActivity.this,"下载失败");
                            return;
                        }
                        if(sp==null){
                            sp=getSharedPreferences(excelName,MODE_PRIVATE);
                        }
                        try {
                           File file= new File(Utils.getAppPath()+"/data/"+fileName);
                           File newFile=new File(Utils.getAppPath()+"/data/"+parame.getString("fileName"));
                           file.renameTo(newFile);
                            sp.edit().putString(parame.getString("name"),parame.getString("fileVersion")).apply();
                            if(parame.getBoolean("default"))
                            sp.edit().putString("default",newFile.getAbsolutePath()).apply();

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

                        hud.dismiss();
                        Utils.toast(ExcelActivity.this,"下载完成");
                        initView();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                hud.dismiss();
                Utils.toast(ExcelActivity.this,"下载失败");
            }
        });
        dialog.show();

    }

    private void initView() {
        try {
            File file = new File(Utils.getAppPath() + "/data/" + parame.getString("fileName"));
           //  file = new File("/storage/emulated/0/jianRMG/data/jianrData.xlsx");
            System.out.println(file.getAbsolutePath()+" "+file.exists());
            excel.start(file);
            setTitle(parame.getString("name")+"  by-"+parame.getString("by"));
            System.out.println("------->"+excel.getReader().getHeight());
        }catch (Exception e){
            e.printStackTrace();
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        excel.stop();
    }
}
