package com.bpa.scalage;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bpa.scalage.app.Main;
import com.bpa.scalage.config.ConfigName;
import com.bpa.scalage.config.MessageName;
import com.bpa.scalage.control.CustomDialog;
import com.bpa.scalage.control.FruitAdapter;
import com.bpa.scalage.control.MyAdapter;
import com.bpa.scalage.data.DataBus;
import com.bpa.scalage.helper.Json;
import com.bpa.scalage.message.MessageLooper;
import com.bpa.scalage.message.MessageManager;
import com.bpa.scalage.mode.Food;
import com.bpa.scalage.mode.Foods.FoodTypes;
import com.bpa.scalage.mode.apimode.ReceiveModel;
import com.bpa.scalage.helper.T;
import com.bpa.scalage.mode.apimode.ReceiveOrganize;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜品选择界面-第一个界面
 */
public class MenuSelectionActivity extends AppCompatActivity{
    //region 定义变量
    public ListView foods_types_name;//导航
    public TextView title;
    private MyAdapter adapter;
    public static int mPosition;
    public ListView fragment_container;//侧面
    public ImageView clist_system;
    /**
     * 当前菜品集合
     */
    public List<String> types_key;
    //endregion

    //region 界面函数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_selection);
        //第二步：绑定控件
        title= (TextView)findViewById(R.id.clist_title);
        foods_types_name= (ListView)findViewById(R.id.tv_typename);
        fragment_container = (ListView) findViewById(R.id.tv_item_foods);
        clist_system=(ImageView) findViewById(R.id.clist_system);
        DataBus.getInstance().dishesCon= MenuSelectionActivity.this;
        RegisterMessage();
        //注册Main函数
        Main.getInstance();
        title.setText(ConfigName.getInstance().Shop_Name);
        //获取菜品数据
        //第三步：准备数据
        //第四步：设计每一个列表项的子布局
        //第五步：定义适配器 控件 -桥梁-数据
        //设置按钮点击后打开设置界面
        Click();
    }

    /**
     * 界面关闭事件
     */
    @Override
    protected void onDestroy() {
        //注销事件
        MessageManager.getInstance().unRegisterMessageReceiver(this);
        super.onDestroy();
    }
    //endregion

    //region 界面点击事件
    /**
     * 点击事件
     */
    public void Click()
    {
        clist_system.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try
                {
                    Intent intent = new Intent(MenuSelectionActivity.this, SystemSetActivity.class);
                    startActivity(intent);
                } catch (Exception e)
                {
                    throw new RuntimeException(e);
                }
            }
        });
    }
    protected void showIdDialog() {

        final EditText et2 = new EditText(MenuSelectionActivity.this);
        et2.setHint("请输入永久版ID");

        new AlertDialog.Builder(MenuSelectionActivity.this)
                .setTitle("免费试用结束：")
                .setMessage(
                        "         尊敬的用户您好，您当前使用的-凯勃荣快捷点餐系统-免费试用版15天已结束，如您还需继续使用，请购买:\n凯勃荣快捷点餐系统——永久版")
                .setView(et2)
                .setPositiveButton(" 解锁永久版 ", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        if (!et2.getText().toString().trim().matches("\\d*")) {
//                            T.show(MenuSelectionActivity.this, "您输的 ID无效，请重新输入 ！");
//                            showIdDialog();
//                            return;
//                        }
                    }
                }).show();

    }

    private void addFood() {
        final CustomDialog.Builder builder = new CustomDialog.Builder(
                this);
        builder.setTitle("请添加菜品：");
        builder.setMessage("添加成功后，可多次添加菜品");
        builder.setPositiveButton("添 加", new DialogInterface.OnClickListener() {
            private Food food;
            public void onClick(DialogInterface dialog, int which) {
                food = new Food();
                food.type = builder.getFoodType();
                food.price = builder.getFoodPrice();
                food.name =  builder.getFoodType()+"-"+builder.getFoodName();

                if (food.name.equals("") || food.type.equals("")
                        || food.price.equals("")) {
                    T.show( MenuSelectionActivity.this, "三项输入内容，都不能为空 ！");
                    return;
                }
                T.show(MenuSelectionActivity.this, "添加成功，还可继续填加 ！");
                food = null;
            }
        });

        builder.setNegativeButton("取 消",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();

    }
    //endregion

    //region 接收事件
    public void RegisterMessage()
    {
        //接收组织查询信息
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.GetOrganize.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    if((msg!=null) && (((String)msg).length()>2)){
                        final ReceiveOrganize model=new Json<ReceiveOrganize>().jsonToobject(ReceiveOrganize.class,((String)msg));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(model.data !=null)
                                {
                                    DataBus.getInstance().organize=model.data;
                                    ConfigName.getInstance().Shop_Id=DataBus.getInstance().organize.id;
                                    if(!ConfigName.getInstance().Shop_Name.equals(model.data.store_Name))
                                    {
                                        ConfigName.getInstance().Shop_Name=model.data.store_Name;
                                        Main.getInstance().SavePZ();
                                    }
                                    //拉取菜菜品
                                    Main.getInstance().GetCaiPin();
                                }else
                                {
                                    T.show(MenuSelectionActivity.this,"未查询到组织,请检查后台配置!店铺AutoKey："+ConfigName.getInstance().AutKey);
                                }
                            }
                        });

                    }
                }else
                {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            T.show(MenuSelectionActivity.this,"服务器异常，请稍后重试!");
                        }
                    });
                }
            }
        });

        //接收菜品消息
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.PullTheDishes.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    if((msg!=null) && (((String)msg).length()>2)){
                        ReceiveModel model=new Json<ReceiveModel>().jsonToobject(ReceiveModel.class,((String)msg));
                        if(model.data!=null && model.data.foodTypes!=null)
                        {
                            DataBus.getInstance().foodTypes=model.data.foodTypes;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    types_key=new ArrayList<>();
                                    for (FoodTypes type:DataBus.getInstance().foodTypes)
                                    {
                                        types_key.add(type.name);
                                    }
                                    if(types_key.size()>0)
                                    {
                                        adapter = new MyAdapter(DataBus.getInstance().dishesCon, types_key.toArray(new String[0]));
                                        foods_types_name.setAdapter(adapter);
                                        foods_types_name.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                                ItemClick(adapterView,view,i,l);
                                            }
                                        });
                                        ItemClick(null,null,0,0);
                                    }

                                    title.setText(ConfigName.getInstance().Shop_Name);
                                }
                            });
                        }
                    }
                }else
                {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            T.show(MenuSelectionActivity.this,"服务器异常，请稍后重试!");
                        }
                    });
                }
            }
        });
    }
    /**
     * Item 点击事件
     * @param adapterView
     * @param view
     * @param position
     * @param id
     */
    public void ItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        //即使刷新adapter
        mPosition=position;
        String str="";
        adapter.notifyDataSetChanged();
        if(view==null)
        {
            String[] key= types_key.toArray(new String[0]);
            if(types_key.size()>0)
            {
                str=key[0];
            }
        }else
        {
            TextView _text=view.findViewById(R.id.tv_zcd);
            if(_text!=null && !_text.getText().toString().isEmpty())
                str=_text.getText().toString();
        }

        if(!str.isEmpty())
        {
            for (FoodTypes ty:DataBus.getInstance().foodTypes) {
                if(ty.name.equals(str) && ty.foods!=null)
                {
                    DataBus.getInstance().foodlist=ty.foods;
                    FruitAdapter adapter = new FruitAdapter(DataBus.getInstance().dishesCon, R.layout.menu_item, DataBus.getInstance().foodlist);
                    fragment_container.setAdapter(adapter);
                    T.show(MenuSelectionActivity.this,"服务器获取菜品成功!");
                }
            }
        }
    }
    //endregion
}