package com.baoshi.swms.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.ArrayMap;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.baoshi.swms.R;
import com.baoshi.swms.bean.Menu;
import com.baoshi.swms.util.GlobalStorage;
import com.baoshi.swms.util.Hint;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 菜单Activity
 */
public class MenuActivity extends AppCompatActivity implements View.OnClickListener {

    private ArrayMap<String, HashMap<String, Menu>> menuMap = new ArrayMap<>();
    private final int columnCount = 4; //每列多少元素节点
    private int back = 0; //回退次数标记

    /**
     * 获取全部的菜单映射信息
     */
    public MenuActivity(){
        this.menuMap = Menu.getMenuNeedVerifyList();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        initData();
        registerEvent(); //注册事件
    }

    //初始化数据
    private void initData() {
        formatData(GlobalStorage.getGlobalStorage().get("menu"));
        if (this.menuMap.size()==0){
            emptyView();
        }else{
            rendingView();
        }
    }

    //格式化信息
    private void formatData(String json) {
        Gson gson = new Gson();
        Map<String, ArrayList<String>> menus = gson.fromJson(json, Map.class);
        ArrayMap<String, HashMap<String, Menu>> menuMap = new ArrayMap<>();
        for (Map.Entry<String, ArrayList<String>> entry : menus.entrySet()) {
            String key = entry.getKey();
            ArrayList<String> values = entry.getValue();
            HashMap<String, Menu> item = new HashMap<>();
            item.put("icon",Objects.requireNonNull(this.menuMap.get(key)).get("icon"));
            for (String itemKey : values){
                if (Objects.requireNonNull(this.menuMap.get(key)).containsKey(itemKey))
                    item.put(itemKey, Objects.requireNonNull(this.menuMap.get(key)).get(itemKey));
            }
            menuMap.put(key,item);
        }
        menuMap.putAll(Menu.getMenuNotNeedVerifyList());
        this.menuMap = menuMap;
    }

    @Override
    public void onBackPressed() {
        if (back==0){
            back++;
            Hint.toastShort(this, "再按一下退出应用", Hint.COMMON);
        }else{
            back = 0;
            finish();
        }
    }

    private void registerEvent() {
        Button logout = findViewById(R.id.logout);
        logout.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        //退出登录时清除当前登录信息
        GlobalStorage storage = GlobalStorage.getGlobalStorage();
        storage.remove("token");
        storage.remove("menu");
        Intent intent = new Intent(MenuActivity.this,LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);//登录界面不进入返回栈
        startActivity(intent);
    }

    //空数据渲染视图
    private void emptyView(){
        GridLayout grid = findViewById(R.id.menu);
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText("您暂未开通任何权限~");
        textView.setTextColor(getResources().getColor(R.color.dark_gray));
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.width =0;
        params.height =100;
        params.rowSpec = GridLayout.spec(0);
        params.columnSpec = GridLayout.spec(0,columnCount,1f);
        grid.addView(textView,params);
    }
    //渲染视图菜单列表
    private void rendingView() {
        GridLayout grid = findViewById(R.id.menu);
        grid.setColumnCount(columnCount);
        int index = 0;
        for (Map.Entry<String, HashMap<String, Menu>> entry : this.menuMap.entrySet()) {
            rendingChild(index,grid,entry.getKey(),entry.getValue().get("icon"));
            int childIndex = 0;
            for (String key : entry.getValue().keySet()) {
                Menu value = entry.getValue().get(key);
                if(key.equals("icon") || value == null)continue;
                if (childIndex%columnCount==0){
                    index++;childIndex = 0;
                }
                rendingChild(index,childIndex,grid,key,value);
                childIndex++;
            }
            if (childIndex>0 && childIndex!=columnCount){
                for (int i=0;i<columnCount-childIndex;i++){
                    rendingChild(index,childIndex+i,grid);
                }
            }
            index++;
        }
    }
    //一级子节点
    private void rendingChild(int index, GridLayout grid, String key, Menu menu){
        LinearLayout container = new LinearLayout(this);
        container.setBackgroundColor(getResources().getColor(R.color.secondary));
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.setMargins(0,10,0,0);
        params.width =0;
        params.height =100;
        params.rowSpec = GridLayout.spec(index);
        params.columnSpec = GridLayout.spec(0,columnCount,1f);

        //ICON渲染
        ImageView icon = new ImageView(container.getContext());
        LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(65, 65);
        lParam.setMarginEnd(7);
        lParam.gravity = Gravity.CENTER;
        lParam.setMarginStart(8);
        icon.setLayoutParams(lParam);
        icon.setBackground(getDrawable(menu!=null ? menu.icon : R.drawable.icon_default));
        container.addView(icon);

        //文本渲染
        TextView textView = new TextView(container.getContext());
        LinearLayout.LayoutParams tParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        tParam.gravity = Gravity.CENTER;
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        textView.setTextSize(20);
        textView.setLayoutParams(tParam);
        textView.setText(key);
        textView.setTextColor(getResources().getColor(R.color.black));
        container.addView(textView);

        grid.addView(container,params);
    }

    //二级子节点
    private void rendingChild(int index,int childIndex,GridLayout grid, String key, Menu menu){
        if (menu==null)return;
        LinearLayout container = new LinearLayout(this);
        container.setPadding(25,25,25,25);
        container.setOrientation(LinearLayout.VERTICAL);
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.width =0;
        params.rowSpec = GridLayout.spec(index);
        params.columnSpec = GridLayout.spec(childIndex,1,1f);

        //ICON渲染
        ImageView icon = new ImageView(container.getContext());
        LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(55, 45);
        lParam.gravity = Gravity.CENTER;
        icon.setLayoutParams(lParam);
        icon.setBackground(getDrawable(menu!=null ? menu.icon : R.drawable.icon_default));
        container.addView(icon);

        //文本渲染
        TextView textView = new TextView(container.getContext());
        LinearLayout.LayoutParams tParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        tParam.gravity = Gravity.CENTER;
        textView.setTextSize(10);
        textView.setTextColor(getResources().getColor(R.color.info));
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        textView.setLayoutParams(tParam);
        textView.setText(key);
        container.addView(textView);

        grid.addView(container,params);
        container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MenuActivity.this, menu.reference);
                startActivity(intent);
            }
        });
    }
    //空节点填充
    private void rendingChild(int index,int childIndex,GridLayout grid){
        TextView textView = new TextView(this);
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.width =0;
        params.rowSpec = GridLayout.spec(index);
        params.columnSpec = GridLayout.spec(childIndex,1,1f);
        grid.addView(textView,params);
    }
}