package com.bpa.scalage;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bpa.scalage.HBL.Dialog.AlertDialogButton;
import com.bpa.scalage.HBL.Dialog.DialogManager;
import com.bpa.scalage.HBL.Logs.MessageLog;
import com.bpa.scalage.Server.APIServer;
import com.bpa.scalage.Server.AddGoodInfo;
import com.bpa.scalage.app.Main;
import com.bpa.scalage.config.ConfigName;
import com.bpa.scalage.config.MessageName;
import com.bpa.scalage.control.ConsumedAdapter;
import com.bpa.scalage.data.DataBus;
import com.bpa.scalage.helper.Json;
import com.bpa.scalage.HBL.Communication.RFIDHelper;
import com.bpa.scalage.helper.SortTools;
import com.bpa.scalage.HBL.Communication.WeightHelper;
import com.bpa.scalage.message.MessageLooper;
import com.bpa.scalage.message.MessageManager;
import com.bpa.scalage.mode.Foods.FoodModel;
import com.bpa.scalage.helper.T;
import com.bpa.scalage.mode.Order.AddSubOrder;
import com.bpa.scalage.mode.Order.BPA_Order;
import com.bpa.scalage.mode.Order.BPA_SubOrder;
import com.bpa.scalage.mode.Users.UserModel;
import com.bpa.scalage.mode.apimode.ReceiveUserAndCartGXModel;
import com.bpa.scalage.mode.apimode.ReceiveUserModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 主程序界面
 */
public class MainActivity extends AppCompatActivity {

    //region 界面控件
    //店铺名称
    private TextView storename;
    //商品名称
    private TextView food_name;
    //价格
    private TextView price;
    //单位 50g
    private TextView vipprice;
    //是否会员，身份
    private TextView is_affiliate1;
    //用户名称
    private TextView username;
    //已消费
    private TextView former_price;
    //初重
    private TextView start_weight;
    //末重
    private TextView end_weight;
    //本次消费重量
    private TextView spend_weight;
    //本次消费金额
    private TextView spend_price;
    //准备页面
    private RelativeLayout welcome;
    //有卡无卡
    private LinearLayout iscartz;
    private RelativeLayout iscartr,iscartk;
    //已消费信息
    public ListView fragment_yxx;
    //endregion

    //region 菜品放置区串口
    private ArrayAdapter<String> mAdapter;
    private static final java.util.Map<String, String> PATH_MAP;
    //波特率集合
    private static final Integer[] BAUDRATES;

    static {
        PATH_MAP = new java.util.LinkedHashMap<String, String>();
        PATH_MAP.put("ttyS3", "/dev/ttyS3");
        PATH_MAP.put("ttyS0", "/dev/ttyS0");
        PATH_MAP.put("ttyS1", "/dev/ttyS1");
        PATH_MAP.put("ttyS2", "/dev/ttyS2");
        PATH_MAP.put("ttyS4", "/dev/ttyS4");
        PATH_MAP.put("ttyP0", "/dev/ttyP0");
        PATH_MAP.put("ttyP1", "/dev/ttyP1");
        PATH_MAP.put("ttyP2", "/dev/ttyP2");
        PATH_MAP.put("ttyP3", "/dev/ttyP3");
        BAUDRATES = new Integer[]{4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000, 576000, 921600, 1000000,};
    }

    private ConcurrentLinkedQueue<Byte> cache = new ConcurrentLinkedQueue<>();
    private boolean mRunning = false;

    private boolean mCartRunning = false;

    /**
     * 检测当前放入的餐盘是否有绑定订单
     */
    private boolean IsBindingOrder=false;
    //endregion

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
        onListener();
    }

    /**
     * 界面关闭事件
     */
    @Override
    protected void onDestroy() {
        T.show(MainActivity.this, "关闭称重界面!");
        if(mRunning)
        {
            mRunning=false;
            WeightHelper.Close();
            RFIDHelper.Close();
        }

        if(mCartRunning)
        {
            mCartRunning=false;
            RFIDHelper.Close();
        }

        MessageManager.getInstance().unRegisterMessageReceiver(this);
        super.onDestroy();
    }

    /**
     * 初始化
     */
    private void Init() {
        storename=findViewById(R.id.tv_storename);
        food_name= findViewById(R.id.tv_food_name);
        price= findViewById(R.id.ma_pic);
        vipprice= findViewById(R.id.vip_price);
        is_affiliate1= findViewById(R.id.tv_is_affiliate1);
        username= findViewById(R.id.tv_username);
//        balance= findViewById(R.id.tv_balance);
        former_price= findViewById(R.id.tv_former_price);
        start_weight= findViewById(R.id.tv_start_weight);
        end_weight= findViewById(R.id.tv_end_weight);
        spend_weight= findViewById(R.id.tv_spend_weight);
        spend_price= findViewById(R.id.tv_spend_price);
        welcome=findViewById(R.id.tv_welcome);
        iscartz=findViewById(R.id.tv_iscartz);
        iscartr=findViewById(R.id.tv_iscartr);
        iscartk=findViewById(R.id.tv_iscartk);
        fragment_yxx=findViewById(R.id.tv_item_consume);
        //当前售卖商品
        RefreshFruit(DataBus.getInstance().SelectFood);
        storename.setText(ConfigName.getInstance().Shop_Name);
    }

    /**
     * 界面事件处理
     */
    private void onListener() {
        //菜品放置区
        try{
            WeightHelper.Open(ConfigName.getInstance().Dishes_Com_Name, ConfigName.getInstance().Dishes_Com_Port,"8N1").OnSource(()->{
                mRunning = true;
                WeightHelper.WeightNotify.ChangeNotify=((s)->{
                    this.runOnUiThread(()->{
                        if (s<50){
                            welcome.setVisibility(View.VISIBLE);
                            RefreshConsumption();
                        }else{
                            welcome.setVisibility(View.GONE);
                            RefreshConsumption();
                        }
                    });
                });
            }).OnFailed(()->{
                DialogManager.showError(this, "称重台通讯失败", AlertDialogButton.OK,null);
                mRunning = false;
            });

            //餐盘感应区域
            RFIDHelper.Open(ConfigName.getInstance().Plate_Com_Name,ConfigName.getInstance().Plate_Com_Port,ConfigName.getInstance().Plate_Com_Format).OnSource(()->{
                mCartRunning=true;
                RFIDHelper.ChipCode.ChangeNotify=(code)->{
                    this.runOnUiThread(()->{
                        if(!code.isEmpty()&&!code.equals("无卡")){
                            DataBus.getInstance().CartNo=code;
                            DataBus.getInstance().CurrentCart=code;
                            ReadApiUserInformation();
                            MessageLog.ShowInfo("执行用户信息获取");
                        }else{
                            if(!DataBus.getInstance().CartNo.isEmpty()&&!DataBus.getInstance().CartNo.equals("无卡")){
                                SendApiConsume();
                                DataBus.getInstance().CartNo="无卡";
                                iscartz.setVisibility(View.GONE);
                                iscartr.setVisibility(View.GONE);
                                iscartk.setVisibility(View.GONE);
                                MessageLog.ShowInfo("执行工单提交");
                            }
                        }
                    });
                };
            }).OnFailed(()->{
                DialogManager.showError(this, "餐盘串口通讯失败", AlertDialogButton.OK,null);
                mCartRunning=false;
            });
        }catch (Exception e){
            Log.e("异常",e.toString());
        }


    }

    /**
     * 根据菜品刷新界面显示
     * @param fruit
     */
    public void  RefreshFruit(FoodModel fruit){
        food_name.setText(fruit.name);
        price.setText("非会员 ¥"+String.format("%.2f",fruit.price)+"/50g");
        vipprice.setText("会员 ¥"+String.format("%.2f",fruit.vipPrice)+"/50g");
    }

    /**
     * 刷新界面显示重量
     */
    public void RefreshConsumption(){

        int tmp=DataBus.getInstance().start_weight- WeightHelper.WeightNotify.getValue();
        if(tmp>0)
        {
            DataBus.getInstance().xf_weight=tmp;//消费重量 tmp/50
            double xjpic= ((double)tmp)/(double)50;
            DataBus.getInstance().xf_sjprice=DataBus.getInstance().SelectFood.price*xjpic;
            DataBus.getInstance().xf_price= DataBus.getInstance().xf_sjprice;
        }

        //初重
        start_weight.setText(String.valueOf(DataBus.getInstance().start_weight)+"g");
        //末重
        end_weight.setText(String.valueOf(WeightHelper.WeightNotify.getValue())+"g");

        //本次消费重量
        spend_weight.setText(String.valueOf(DataBus.getInstance().xf_weight)+"g");
        //本次消费金额
        spend_price.setText("¥"+ String.format("%.2f",DataBus.getInstance().xf_price));
        IsBindingOrder=true;
    }

    /**
     * 发送API进行消费
     */
    public void SendApiConsume(){
        if(!IsBindingOrder){ ReadApiUserInformation(); }
        if(IsBindingOrder){
            IsBindingOrder=false;
            if(DataBus.getInstance().xf_weight>=ConfigName.getInstance().MinWeight)//5g以上开始计费
            {
                try{
                    String orderId = DataBus.getInstance().weighOrderDto.id;
                    String goodId = DataBus.getInstance().SelectFood.id;
                    String goodsName=DataBus.getInstance().SelectFood.name;
                    String chipCode = DataBus.getInstance().CurrentCart;
                    APIServer.CreateOrder(new AddGoodInfo(orderId,goodId,goodsName,DataBus.getInstance().xf_weight,chipCode),null,(error)->{
                        this.runOnUiThread(()->{
                            T.show(MainActivity.this,error);
                        });
                    });
                }catch(Exception e){
                }
            }else
            {
                DataBus.getInstance().xf_weight=0;
                DataBus.getInstance().xf_price=0;
                DataBus.getInstance().xf_sjprice=0;
                runOnUiThread(()->{ T.show(MainActivity.this,"消费重量小于 "+ConfigName.getInstance().MinWeight+"g，不予计费");});
            }
        }else{
            runOnUiThread(()->{ T.show(MainActivity.this,"请先打开小程序扫描餐盘码");});
        }

    }

    /**
     * 调用API查询用户信息
     */
    public void ReadApiUserInformation() {
        APIServer.GetOrderInfo(DataBus.getInstance().CartNo,(s)->{
            this.runOnUiThread(()->{
                iscartz.setVisibility(View.VISIBLE);
                iscartr.setVisibility(View.VISIBLE);
                iscartk.setVisibility(View.VISIBLE);
                ConsumedAdapter adapter = new ConsumedAdapter(MainActivity.this, R.layout.menu_item, s.goodsInfo);
                fragment_yxx.setAdapter(adapter);
                former_price.setText("¥"+ String.format("%.2f",s.totalAmount));//已消费数据显示
                if(s.memberInfo!=null){
                    is_affiliate1.setText(s.memberInfo.isMember?"会员":"非会员");
                    username.setText(s.memberInfo.name);
                }else{
                    is_affiliate1.setText("非会员");
                    username.setText("未注册");
                }

                DataBus.getInstance().start_weight=  WeightHelper.WeightNotify.getValue();
                DataBus.getInstance().xf_weight=0;
                DataBus.getInstance().xf_price=0;
                DataBus.getInstance().xf_sjprice=0;
                RefreshConsumption();
            });
        },(error)->{
            IsBindingOrder=false;
            this.runOnUiThread(()->{
                T.show(MainActivity.this,error);
            });
        });
    }
}