package com.example.bpa;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.NetworkCapabilities;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bpa.Model.OrderA;
import com.example.bpa.Model.ReceiveOrder;
import com.example.bpa.Model.ResVersion;
import com.example.bpa.Model.SuOrderA;
import com.example.bpa.app.Main;
import com.example.bpa.config.ConfigName;
import com.example.bpa.config.DataBus;
import com.example.bpa.config.MessageName;
import com.example.bpa.db.QueryDB;
import com.example.bpa.db.mode.BPA_GOODS;
import com.example.bpa.db.mode.BPA_ORDER;
import com.example.bpa.db.mode.BPA_SUBORDER;
import com.example.bpa.helper.Json;
import com.example.bpa.helper.MQTT;
import com.example.bpa.helper.ModbusTcpHelper;
import com.example.bpa.helper.ModbusTcpServer;
import com.example.bpa.helper.T;
import com.example.bpa.helper.UpdateManager;
import com.example.bpa.helper.WrapContentLinearLayoutManager;
import com.example.bpa.message.MessageLooper;
import com.example.bpa.message.MessageManager;
import com.example.bpa.service.BusinessServer;
import com.example.bpa.service.DeviceData;
import com.example.bpa.service.OrderServer;
import com.example.bpa.service.ScanCodeServer;
import com.example.bpa.view.adapter.makegood_adapter;
import com.example.bpa.view.adapter.order_adapter;
import com.example.bpa.view.fragment.CloudFragment;
import com.example.bpa.view.fragment.HeplerFragment;
import com.example.bpa.view.fragment.HomeFragment;
import com.example.bpa.view.fragment.SsjkFragment;
import com.example.bpa.view.fragment.SystemCapabilitiesFragment;
import com.example.bpa.view.fragment.SystemSetFragment;
import com.example.bpa.view.mode.MakeStatus;
import com.example.bpa.view.mode.ResGoodsMake;
import com.example.bpa.view.mode.ResGoodsRecipe;
import com.example.bpa.view.mode.mainGoods;

import java.net.IDN;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity implements View.OnClickListener {

    //region 界面变量
    //标题
    private TextView clist_title,version;
    //返回 云端 系统功能 系统设置 系统帮助
    private ImageView CloudUpdates, SystemCapabilities, SystemSettings, SystemHelp, HomeMain, ColseMain, RealTimeMonitoring;
    //页面
    private FrameLayout fragment_container;
    //云端更新版本
    private UpdateManager mUpdateManager;
    //endregion

    //region 界面
    //主页
    public HomeFragment homeFragment = new HomeFragment();
    //更新
    public CloudFragment cloudFragment = new CloudFragment();
    //系统功能
    public SystemCapabilitiesFragment systemCapabilitiesFragment = new SystemCapabilitiesFragment();
    //系统设置
    public SystemSetFragment systemSetFragment = new SystemSetFragment();
    //系统帮助
    public HeplerFragment heplerFragment = new HeplerFragment();
    //硬件监控
    public SsjkFragment ssjkFragment = new SsjkFragment();
    //endregion

    //region 私有函数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
        initEvents();
        initBusiness();
    }

    /**
     * 界面关闭
     */
    @Override
    protected void onDestroy() {
        MQTT.get().ConnMqttBroken(false);//释放mqtt
        ModbusTcpHelper.get().release();//释放modbus
        super.onDestroy();
    }
    //endregion

    //region 公有函数

    /**
     * 初始化
     */
    private void Init() {
        clist_title = findViewById(R.id.clist_title);
        version= findViewById(R.id.version);
        CloudUpdates = findViewById(R.id.CloudUpdates);
        SystemCapabilities = findViewById(R.id.SystemCapabilities);
        SystemSettings = findViewById(R.id.SystemSettings);
        SystemHelp = findViewById(R.id.SystemHelp);
        HomeMain = findViewById(R.id.HomeMain);
        ColseMain = findViewById(R.id.ColseMain);
        fragment_container = findViewById(R.id.fragment_container);
        RealTimeMonitoring = findViewById(R.id.RealTimeMonitoring);
        clist_title.setText(ConfigName.getInstance().Shop_Name);
        version.setText(ConfigName.getInstance().Version);
        ShowFragment(homeFragment, "系统主页");
        DataBus.getInstance().UpdateMainGoods();
        mUpdateManager = new UpdateManager(MainActivity.this);
    }

    /**
     * 初始化按钮事件
     */
    private void initEvents() {
        //设置四个Tab的点击事件
        CloudUpdates.setOnClickListener(this);
        SystemCapabilities.setOnClickListener(this);
        SystemSettings.setOnClickListener(this);
        SystemHelp.setOnClickListener(this);
        HomeMain.setOnClickListener(this);
        ColseMain.setOnClickListener(this);
        RealTimeMonitoring.setOnClickListener(this);
    }

    /**
     * 初始化业务
     */
    private void initBusiness() {
        Main.getInstance().ToggleEnvironment();
        //PLC数据监控
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ModbusTcpServer.get().Connect();
                } catch (Exception e) {

                }
            }
        }).start();
        //ModbusTcpServer.get().ReconnectModbus();
        //MQTT数据监听
        OrderServer.Get().MqttInit();
        //消息中心
        RegisterMessage();
    }

    /**
     * 检测版本更新
     */
    public void UpdateVersion() {
        //检测版本更新
        Main.getInstance().UpdateVersion();
        //mUpdateManager.checkVersion(null);
    }
    //endregion

    //region 点击事件

    /**
     * 本页面点击事件监听
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.CloudUpdates://系统更新按钮
                UpdateVersion();
                break;
            case R.id.SystemCapabilities://系统功能按钮
                ShowFragment(systemCapabilitiesFragment, "功能菜单");
                break;
            case R.id.SystemSettings://系统设置按钮
                ShowFragment(systemSetFragment, "系统设置");
                break;
            case R.id.SystemHelp://系统帮助按钮
//                BPA_ORDER order=new BPA_ORDER();
//                order.thirdPartyID="手动下单";
//                order.status=0;
//                order.deviceID = ConfigName.getInstance().DeviceId;
//                order.userID = ConfigName.getInstance().user.userID;
//                QueryDB.AddOrder(order);
//                for (mainGoods mode: DataBus.getInstance().mainGoods)
//                {
//                    BPA_SUBORDER suborder=new BPA_SUBORDER();
//                    suborder.deviceID = ConfigName.getInstance().DeviceId;
//                    suborder.userID = ConfigName.getInstance().user.userID;
//                    suborder.orderID = order.id;
//                    suborder.goodsID = mode.id;
//                    suborder.number = 1;
//                    suborder.status=0;
//                    suborder.goodImg=mode.url;
//                    QueryDB.AddSubOrder(suborder);
//                }
//                MessageManager.getInstance().sendMessage(MessageName.ShowOrderMakeForm.name(),order.id);

                //Main.getInstance().GetOrder("456715513230397440");


                if(OrderID.isEmpty())
                {
                    T.show(MainActivity.this, "无制作中饮品！");
                }else
                {
                    ShowDialog(OrderID);
                }


                //Main.getInstance().GetOrder(OrderID);
                //ShowFragment(heplerFragment, "系统帮助");
                break;
            case R.id.HomeMain://主页
                ShowFragment(homeFragment, "系统主页");
                break;
            case R.id.ColseMain://关闭主窗体
                ColseActive();
                break;
            case R.id.RealTimeMonitoring://关闭主窗体
                ShowFragment(ssjkFragment, "实时监控");
                break;
        }
    }

    /**
     * 当前选中窗体
     */
    public Fragment SelectFragment = null;

    /**
     * 打开窗体
     */
    public void ShowFragment(Fragment fragment, String Text) {
        clist_title.setText(Text);
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        if (SelectFragment != null) {
            transaction.remove(SelectFragment);
        }
        transaction.add(R.id.fragment_container, fragment);
        transaction.commit();
        SelectFragment = fragment;
    }

    /**
     * 关闭主窗体
     */
    public void ColseActive() {
        // 1.创建弹框对象,显示在当前页面
        AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
        // 2.编辑弹框样式
        // 2.1 创建标题
        ab.setTitle("注销安全提示");
        // 2.3 设置图标
        ab.setIcon(R.mipmap.ts);
        // 2.4 设置内容
        ab.setMessage("您是否注销登录？");
        // 2.5 设置按钮
        ab.setPositiveButton("取消", null);
        ab.setNeutralButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 实现程序的退出，结束当前
                MainActivity.this.finish();
            }
        });
        // 3.创建弹框
        ab.create();
        // 4.显示弹框
        ab.show();
    }

    AlertDialog alg = null;
    public String OrderID="";
    /**
     * 显示订单窗口
     *
     * @param order
     */
    public void AddOrder(OrderA order) {
        try {
            if (order.orderDetail == null || order.orderDetail.size() <= 0) {
                T.show(MainActivity.this, "子订单不能为空！");
                return;
            }

            if (!QueryDB.GetOrderIs(order.id)) {
                BPA_ORDER order1 = new BPA_ORDER();
                order1.thirdPartyID = "扫码下单";
                order1.status = 0;
                order1.deviceID = ConfigName.getInstance().DeviceId;
                order1.userID = ConfigName.getInstance().user.userID;
                order1.id = order.id;
                order1.sortId = order.sortId;

                QueryDB.AddOrder(order1);
                for (SuOrderA item : order.orderDetail)//新增子订单
                {
                    BPA_SUBORDER suborder = new BPA_SUBORDER();
                    suborder.id=item.id;
                    suborder.deviceID = ConfigName.getInstance().DeviceId;
                    suborder.userID = ConfigName.getInstance().user.userID;
                    suborder.orderID = order.id;
                    suborder.goodsID = item.goods_Id;
                    suborder.number = 1;
                    suborder.status = 0;
                    suborder.goodImg = item.goodImg;
                    QueryDB.AddSubOrder(suborder);
                }
            }

            DataBus.getInstance().OrderSM = order;
            //显示弹窗
            ShowDialog(order.id);
            //初始化数据
        } catch (Exception ex) {
        }
    }

    /**
     * 显示制作订单详情
     * @param id
     */
    public void ShowDialog(String id)
    {
        try {
            OrderID= id;
            ArrayList<BPA_SUBORDER> sub = QueryDB.GetSubOrderList(id);
            DataBus.getInstance().GoodsSMMake.clear();
            for (BPA_SUBORDER k : sub) {
                ResGoodsMake make = new ResGoodsMake();
                make.recipes = QueryDB.GetGoodsSrecipeList(k.goodsID);
                BPA_GOODS good= QueryDB.GetGoodsId(k.goodsID);
                if(good.name!=null)
                {
                    make.good = QueryDB.GetGoodsId(k.goodsID);
                    make.subOrder = k;

                    make.makeMs = "";
                    make.makeProcess = 0;
                    if (k.status == 0) {
                        make.makeStatus = MakeStatus.等待制作;
                    } else if (k.status == 1) {
                        make.makeStatus = MakeStatus.制作中;
                    } else {
                        make.makeStatus = MakeStatus.制作完成;
                        make.makeMs = "";
                        make.makeProcess = 100;
                        for (ResGoodsRecipe recipe : make.recipes) {
                            recipe.makeProcess = 100;
                        }
                    }
                    // if(!make.makeStatus.equals(MakeStatus.制作完成))
                    {
                        DataBus.getInstance().GoodsSMMake.add(make);
                    }
                }
            }
            if(DataBus.getInstance().GoodsSMMake.size()<=0)
            {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        T.show(MainActivity.this, "无可制作的订单!");
                    }
                });
                return;
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (alg == null) {
                        alg = new AlertDialog.Builder(MainActivity.this).create();
                    }

                    if (!MainActivity.this.isFinishing())
                    {
                        if (!alg.isShowing())
                            alg.show();
                        Window win = alg.getWindow();
                        win.setContentView(R.layout.order_dialog);

                        WindowManager m = getWindowManager();
                        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高

                        android.view.WindowManager.LayoutParams p = win.getAttributes();  //获取对话框当前的参数值
                        p.height = (int) (d.getHeight() * 1);   //高度设置为屏幕的0.3
                        p.width = (int) (d.getWidth() * 1);    //宽度设置为屏幕的0.5
                        win.setAttributes(p);     //设置生效

                        ImageView gongneng_fanhui = win.findViewById(R.id.gongneng_fanhui);
                        TextView gongneng_title = win.findViewById(R.id.gongneng_title);
                        RecyclerView Order = win.findViewById(R.id.Order);
                        gongneng_title.setText("制作订单详情");

                        Order.setLayoutManager(new WrapContentLinearLayoutManager(win.getContext(), LinearLayoutManager.HORIZONTAL, false));
                        DataBus.getInstance().orderadapter = new order_adapter(win.getContext());
                        Order.setAdapter(DataBus.getInstance().orderadapter);
                        gongneng_fanhui.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                alg.dismiss();
                            }
                        });
                    }
                }
            });

            //初始化数据
        } catch (Exception ex) {
        }
    }

    /**
     * 关闭弹窗
     */
    public void CloseDialog()
    {
        if(alg!=null)
        {
            T.show(MainActivity.this, "制作完成，关闭制作窗体!");
            alg.dismiss();
        }
    }
    //endregion

    //region 接收事件

    public void RegisterMessage() {
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.GetOrderInformation.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    if ((msg != null) && (((String) msg).length() > 2)) {
                        ReceiveOrder model = new Json<ReceiveOrder>().jsonToobject(ReceiveOrder.class, ((String) msg));
                        if (model.data != null) {
                            AddOrder(model.data);
                            T.show(MainActivity.this, "查询成功!");
                        }else
                        {
                            T.show(MainActivity.this, "没有查询到该订单!");
                        }
                    } else {
                        T.show(MainActivity.this, "服务器异常，请稍后重试!");
                    }
                }
            }
        });

        MessageManager.getInstance().registerMessageReceiver(this, MessageName.ShowOrderMakeForm.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    ShowDialog((String) msg);
                }
            }
        });
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.CloseOrderMakeForm.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CloseDialog();
                    }
                });
            }
        });

        //版本更新
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.UpdateVersion.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    if ((msg != null) && (((String) msg).length() > 2)) {
                        ResVersion model = new Json<ResVersion>().jsonToobject(ResVersion.class, ((String) msg));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mUpdateManager.checkVersion(model.data);
                            }
                        });
                    } else {
                        T.show(MainActivity.this, "服务器异常，请稍后重试!");
                    }
                }
            }
        });
    }
    //endregion
}