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.app.Main;
import com.bpa.scalage.config.ConfigName;
import com.bpa.scalage.config.MessageName;
import com.bpa.scalage.control.ConsumedAdapter;
import com.bpa.scalage.control.FruitAdapter;
import com.bpa.scalage.data.DataBus;
import com.bpa.scalage.helper.ByteHelper;
import com.bpa.scalage.helper.Json;
import com.bpa.scalage.helper.SortTools;
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.UserAndCart.UserAndCartMerge;
import com.bpa.scalage.mode.Users.UserModel;
import com.bpa.scalage.mode.apimode.ReceiveUserAndCartGXModel;
import com.bpa.scalage.mode.apimode.ReceiveUserModel;
import com.lztek.toolkit.SerialPort;
import com.pc_rfid.api.PC_API;
import com.pc_rfid.api.RFdata;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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 SerialPort mSerialPort;
    private boolean mRunning = false;

    private boolean mCartRunning = false;
    //endregion

    //region jar包访问
    //硬件访问包
    private com.lztek.toolkit.Lztek mLztek;
    //刷卡器读取
    private static RFdata rFRead=new RFdata();
    //操作读卡设备
    private PC_API api=new PC_API();
    //endregion

    //region 私有进入函数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
        onListener();
    }
    //endregion

    //region 界面关闭事件
    @Override
    protected void onDestroy() {
        T.show(MainActivity.this, "关闭称重界面!");
        if(mRunning)
        {
            mRunning=false;
            mSerialPort.close();
            api.PC_Close();
        }

        if(mCartRunning)
        {
            mCartRunning=false;
            api.PC_Close();
        }

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

    //region 私有函数
    public String getIdentity() {
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
        String identity = preference.getString("identity", null);
        if (identity == null) {
            identity = java.util.UUID.randomUUID().toString();
            preference.edit().putString("identity", identity);
        }
        return identity;
    }
    /**
     * 初始化
     */
    private void Init() {
        mLztek = com.lztek.toolkit.Lztek.create(this);
        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);
        RegisterMessage();
    }

    /**
     * 界面事件处理
     */
    private void onListener() {
        //菜品放置区
        if (null == (mSerialPort = mLztek.openSerialPort(ConfigName.getInstance().Dishes_Com_Name, ConfigName.getInstance().Dishes_Com_Port, 8, 0, 1, 0))) {
            String message = ConfigName.getInstance().Dishes_Com_Name + "[" + ConfigName.getInstance().Dishes_Com_Port + "]" + ", " + ConfigName.getInstance().Dishes_Com_Port + "端口打开失败";
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("错误");
            builder.setMessage(message);
            builder.setNegativeButton("确定", null);
            builder.create();
            builder.show();
            mRunning = false;
        } else {
            mRunning = true;
            runRead();
            processData();
            T.show(MainActivity.this, "称重模块正在运行!");
        }

        //餐盘感应区域
        if(api.PC_OpenCOM(ConfigName.getInstance().Plate_Com_Name,ConfigName.getInstance().Plate_Com_Port,ConfigName.getInstance().Plate_Com_Format)){
            Log.i("DEBUG", "打开读卡Cart串口成功");
            api.PC_OpenDevice(rFRead);
            ReadCraK();
            mCartRunning=true;
            //api.PC_ReadCfgBlock(rFRead,(byte) 1);//读配置
            if(api.PC_OpenAnt_One(rFRead, (byte) 1))
            {
                Log.i("DEBUG", "打开1号天线口成功");
                rFRead.clear();
            }else
            {
                Log.i("DEBUG", "打开1号天线口失败");
            }
            T.show(MainActivity.this, "餐盘感应区正在运行!");

        }else
            mCartRunning=false;
    }
    //endregion

    //region 循环读卡流程
    private void ReadCraK()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mCartRunning) {
                    try {
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(mCartRunning && welcome.getVisibility()!=View.VISIBLE)
                                {
                                    api.PC_InventoryTag(rFRead,(byte)4);//循环读取卡片信息
                                    String Value=rFRead.getReceiveData();
                                    if(Value.length()==51)
                                    {

                                        try
                                        {
                                            String CartHao= Value.replace(" ","").substring(14, 30);
                                            if(DataBus.getInstance().CartNo=="" && !CartHao.equals(DataBus.getInstance().CartNo))
                                            {
                                                //T.show(MainActivity.this,CartHao);
                                                DataBus.getInstance().CartNo=CartHao;
                                                ReadApiUserInformation();
                                            }
                                        } catch (Exception e) {
                                            T.show(MainActivity.this,"异常"+e);
                                        }
                                    }else
                                    {
                                        //如果刚才的卡号不为空,现在为空的话 需要提交计算金额
                                        if(!DataBus.getInstance().CartNo.isEmpty() || DataBus.getInstance().CartNo!="" )
                                        {
                                            SendApiConsume();
                                        }
                                        DataBus.getInstance().CartNo="";
                                        iscartz.setVisibility(View.GONE);
                                        iscartr.setVisibility(View.GONE);
                                        iscartk.setVisibility(View.GONE);
                                    }
                                }
                            }
                        });
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
    //endregion

    //region 菜品放置区串口
    /**
     * 串口处理函数
     */
    private void runRead() {
        if (null == mSerialPort) {
            mRunning = false;
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mRunning) {
                    final byte[] data = null != mSerialPort ? read() : null;
                    if (null == data) continue;
                    for (int i = 0; i < data.length; i++)
                        cache.add(data[i]);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }

    private byte[] read() {
        if (null == mSerialPort) {
            return null;
        }

        java.io.InputStream input = null;
        try {
            input = mSerialPort.getInputStream();

            byte[] buffer = new byte[1024];
            int len = input.read(buffer);
            return len > 0 ? java.util.Arrays.copyOfRange(buffer, 0, len) : null;
        } catch (Exception e) {
            android.util.Log.d("#ERROR#", "[COM]Read Faild: " + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 数据解析函数
     */
    private void processData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] temp = new byte[12];
                while (mRunning) {
                    while (cache.size() >= 12) {
                        byte flag = cache.poll();
                        if (flag != 0x01) continue;
                        byte cmd = cache.poll();
                        if (cmd != 0x03) continue;
                        temp[0] = 0x01;
                        temp[1] = 0x03;
                        for (int i = 2; i < 12; i++) {
                            temp[i] = cache.poll();
                        }
                        //  01 03 2B 30 30 31 2E 30 30 30 23 9D
                        //模块功能  +  0  0  1  .  0  0  0  校验
                        //1KG显示+001.000ASCII代码编写
                        //+代表2B -2E
                        //0代表30
                        //1代表31
                        //.小数点代表2E

                        //取前10位 计算校验码
                        byte[] validateTemp = new byte[10];
                        System.arraycopy(temp, 0, validateTemp, 0, 10);
                        int res = ByteHelper.getCRC2(validateTemp);
                        //取后两位校验码
                        byte[] rawCode = new byte[4];
                        System.arraycopy(temp, 10, rawCode, 2, 2);
                        int raw = ByteHelper.byteToInt(rawCode);
                        if (raw == res) //校验成功
                        {
                            //+001.000 heavy[2]==0x2B
                            final byte[] heavy = new byte[7];
                            System.arraycopy(temp, 3, heavy, 0, 7);
                            String text = new String(heavy);
                            if(temp[2]==0x2B)//如果是正数
                            {
                                int k= (int) (Double.parseDouble(text)*1000);
                                DataBus.getInstance().weight=k;
                            }else
                            {
                                DataBus.getInstance().weight=0;
                            }
                            RefreshWeight();
                        }
                    }
                }
            }
        }).start();
    }
    //endregion

    //region 界面操作函数
    public void RefreshWeight()
    {
        //计算价格
        if(DataBus.getInstance().CartNo.equals("") || DataBus.getInstance().CartNo.isEmpty())//记录初始重量
        {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                T.show(MainActivity.this,e.getMessage());
            }
            DataBus.getInstance().start_weight=DataBus.getInstance().weight;
            DataBus.getInstance().xf_weight=0;
            DataBus.getInstance().xf_price=0;
            DataBus.getInstance().xf_sjprice=0;
        }else //计算实时消费,与显示消费
        {
            int tmp=DataBus.getInstance().start_weight-DataBus.getInstance().weight;
            if(tmp>=5 && DataBus.getInstance().selectuser!=null)//80g 5g以上开始计费
            {

                //非会员
                double pic=DataBus.getInstance().selectuser.Isvip? DataBus.getInstance().SelectFood.vipPrice: DataBus.getInstance().SelectFood.price;//6.9
                DataBus.getInstance().xf_weight=tmp;//消费重量 tmp/50
                double xjpic= ((double)tmp)/(double)50;
                DataBus.getInstance().xf_price=((double)(pic))*xjpic;
                DataBus.getInstance().xf_sjprice=((double)(DataBus.getInstance().SelectFood.price))*xjpic;
            }else
            {
                DataBus.getInstance().xf_weight=0;
                DataBus.getInstance().xf_price=0;
                DataBus.getInstance().xf_sjprice=0;
            }
        }
        //更新界面
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (DataBus.getInstance().weight<50)
                {
                    welcome.setVisibility(View.VISIBLE);
                }else
                {
                    welcome.setVisibility(View.GONE);
                    RefreshConsumption();
                }
            }
        });
    }
    /**
     * 根据菜品刷新界面显示
     * @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()
    {
        //初重
        start_weight.setText(String.valueOf(DataBus.getInstance().start_weight)+"g");
        //末重
        end_weight.setText(String.valueOf(DataBus.getInstance().weight)+"g");
        //本次消费重量
        spend_weight.setText(String.valueOf(DataBus.getInstance().xf_weight)+"g");
        //本次消费金额
        spend_price.setText("¥"+ String.format("%.2f",DataBus.getInstance().xf_price));
    }

    /**
     * 发送API进行消费
     */
    public void SendApiConsume()
    {
        //满足条件 创建子订单
        if(DataBus.getInstance().xf_price>0 && DataBus.getInstance().selectMerge!=null
                && !DataBus.getInstance().selectMerge.orderId.isEmpty() && DataBus.getInstance().selectMerge.orderList!=null)
        {
            DataBus.getInstance().Ch=DataBus.getInstance().CartNo;
            DataBus.getInstance().addsuborder=new AddSubOrder();
            DataBus.getInstance().addsuborder.orderId=DataBus.getInstance().selectMerge.orderList.id;
            DataBus.getInstance().addsuborder.goodId=DataBus.getInstance().SelectFood.id;
            DataBus.getInstance().addsuborder.goodName=DataBus.getInstance().SelectFood.name;
            DataBus.getInstance().addsuborder.storeId=ConfigName.getInstance().Shop_Id;
            DataBus.getInstance().addsuborder.gooodOriginPrice=DataBus.getInstance().xf_price;
            DataBus.getInstance().addsuborder.goodsRealPrice=DataBus.getInstance().xf_sjprice;
            String bz= String.format("%.2f", DataBus.getInstance().selectuser.Isvip? DataBus.getInstance().SelectFood.vipPrice: DataBus.getInstance().SelectFood.price);
            DataBus.getInstance().addsuborder.remark=bz;
            DataBus.getInstance().addsuborder.cookingStatus=1;
            DataBus.getInstance().addsuborder.consumeUnit=String.valueOf(DataBus.getInstance().xf_weight);
            Main.getInstance().AddSubOrder(new Json<AddSubOrder>().objectToJson(AddSubOrder.class,DataBus.getInstance().addsuborder));
        }
    }

    /**
     * 调用API查询用户信息
     */
    public void ReadApiUserInformation()
    {
        //获取用户的关联关系
        Main.getInstance().GetUserAndOrderGX(DataBus.getInstance().CartNo);
    }
    //endregion

    //region 接收事件

    public void RegisterMessage()
    {
        //接收用户关联关系查询接口
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.GetUserAndCartGX.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    if((msg!=null) && (((String)msg).length()>2)){
                        ReceiveUserAndCartGXModel model=new Json<ReceiveUserAndCartGXModel>().jsonToobject(ReceiveUserAndCartGXModel.class,((String)msg));
                        if(model.data==null ||model.data.size()==0)
                            DataBus.getInstance().selectMerge=null;
                        else if(model.data.size()>0)
                            DataBus.getInstance().selectMerge=model.data.get(0);
                        if(model.data==null ||model.data.size()==0)
                        {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    former_price.setText("¥"+ String.format("%.2f",0.00));//已消费
                                    T.show(MainActivity.this,"请先用微信扫码下单!");
                                }
                            });
                        }else
                        {
                            //查询用户信息-是否会员信息
                            Log.i("当前用户信息", DataBus.getInstance().selectMerge.userId);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    iscartz.setVisibility(View.VISIBLE);
                                    iscartr.setVisibility(View.VISIBLE);
                                    iscartk.setVisibility(View.VISIBLE);
                                    //region 获取已消费金额
                                    double yxfprice=0;

                                    List<BPA_SubOrder> orders = new ArrayList<>();
                                    if(DataBus.getInstance().selectMerge.orderList!=null)
                                    {
                                        BPA_Order order= DataBus.getInstance().selectMerge.orderList;
                                        if(order!=null && order.subOrderList!=null && order.subOrderList.size()>0)
                                        {
                                            orders=SortTools.listClassSort(order.subOrderList);
                                            for (BPA_SubOrder suorder :order.subOrderList)
                                            {
                                                yxfprice+= suorder.goodsRealPrice;
                                            }
                                        }
                                    }
                                    ConsumedAdapter adapter = new ConsumedAdapter(MainActivity.this, R.layout.menu_item, orders);
                                    fragment_yxx.setAdapter(adapter);
                                    //endregion
                                    former_price.setText("¥"+ String.format("%.2f",yxfprice));//已消费
                                }
                            });
                            //查询是否会员
                            Main.getInstance().GetUser(DataBus.getInstance().selectMerge.userId);
                        }
                    }
                }else
                {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            T.show(MainActivity.this,"服务器异常，请稍后重试!");
                        }
                    });
                }
            }
        });
        //接收用户查询接口
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.GetUserInformation.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    Log.i("查询用户会员信息", (String)msg);
                    if((msg!=null) && (((String)msg).length()>2)){
                        ReceiveUserModel model=new Json<ReceiveUserModel>().jsonToobject(ReceiveUserModel.class,((String)msg));

                        if(model.data!=null)
                        {
                            DataBus.getInstance().selectuser=model.data;
                            if(DataBus.getInstance().selectuser.isDeleted==0&& !DataBus.getInstance().selectuser.memberInfo_Id.isEmpty())
                            {
                                DataBus.getInstance().selectuser.Isvip=true;
                            }else
                            {
                                DataBus.getInstance().selectuser.Isvip=false;
                            }
                        }else
                        {
                            UserModel mode=new UserModel();
                            mode.nickName="游客";
                            mode.sex=0;//性别 未知
                            mode.platformType=1;//微信
                            mode.platformMemberId="987654321";
                            mode.isDeleted=0;
                            mode.Isvip=false;
                            DataBus.getInstance().selectuser=mode;
                        }

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                is_affiliate1.setText(DataBus.getInstance().selectuser.Isvip?"会员":"非会员");
                                username.setText(DataBus.getInstance().selectuser.nickName);
                                T.show(MainActivity.this,"查询用户成功!");
                            }
                        });
                    }
                }else
                {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            T.show(MainActivity.this,"服务器异常，请稍后重试!");
                        }
                    });
                }
            }
        });
        //创建子订单返回
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.AddSuOrderUrl.name(), new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    Log.i("创建子订单结果", (String)msg);
                    if((msg!=null) && (((String)msg).length()>2)){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                String str=String.format("用户消费成功!\n当前用户:%s\n当前卡号:%s\n当前消费重量:%sg\n当前消费金额:%s元\n",
                                        DataBus.getInstance().selectuser.nickName,
                                        DataBus.getInstance().Ch,
                                        DataBus.getInstance().addsuborder.consumeUnit,
                                        String.format("%.2f",DataBus.getInstance().addsuborder.goodsRealPrice));
                                Log.i("DEBUG", str);

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