package com.example.bpa.service;

import android.util.Log;

import com.example.bpa.Model.BPAPackage;
import com.example.bpa.Model.BPA_GoodsInfo;
import com.example.bpa.Model.BPA_HeartPackage;
import com.example.bpa.Model.BatchingsInfo;
import com.example.bpa.Model.Batchingstechnology;
import com.example.bpa.Model.GoodsBom;
import com.example.bpa.Model.GyAction;
import com.example.bpa.Model.IMessage;
import com.example.bpa.Model.IRun;
import com.example.bpa.Model.IThread;
import com.example.bpa.Model.Message_HeartModel;
import com.example.bpa.Model.PushDeviceGoods;
import com.example.bpa.Model.TechnologyActions;
import com.example.bpa.config.ConfigName;
import com.example.bpa.db.QueryDB;
import com.example.bpa.db.mode.BPA_GOODS;
import com.example.bpa.db.mode.BPA_GOODSRECIPE;
import com.example.bpa.db.mode.BPA_MATERIAL;
import com.example.bpa.db.mode.BPA_SILOSANDMATERIAL;
import com.example.bpa.db.mode.BPA_SUBORDER;
import com.example.bpa.helper.AES;
import com.example.bpa.helper.Json;
import com.example.bpa.helper.MQTT;
import com.example.bpa.helper.MessageLog;
import com.example.bpa.helper.ThreadManager;
import com.example.bpa.view.mode.ResReceiveOrder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 订单服务
 * 收发订单、订单预警、接收云端订单信息
 */
public class OrderServer {

    //region 私有单例
    private static volatile OrderServer _instance;

    public static OrderServer Get() {
        if (_instance == null)
            _instance = new OrderServer();
        return _instance;
    }

    private OrderServer() {
    }
    //endregion

    //region 变量
    /**
     * 订单接收队列
     */
    ConcurrentLinkedQueue<ResReceiveOrder> Commoditys = new ConcurrentLinkedQueue<ResReceiveOrder>();
    //endreigon

    //region 公共函数

    /**
     * 初始化
     */
    public void Init()
    {
//        ThreadManager.Get().StartLong("订单服务", true, new IThread() {
//            @Override
//            public void Run() throws InterruptedException {
//                MessageLog.ShowInfo("我是订单服务！");
//                Thread.sleep(2000);
//            }
//            @Override
//            public void RunComplete() throws InterruptedException {
//            }
//        });


    }

    /**
     * MQTT初始化
     */
    public void MqttInit()
    {
        ConfigName.getInstance().ClientId=ConfigName.getInstance().AutKey;
        ConfigName.getInstance().DevId=ConfigName.getInstance().AutKey;

        if(ConfigName.getInstance().AutKey.contains("."))
        {
            String[] str= ConfigName.getInstance().AutKey.split("[.]");
            ConfigName.getInstance().ClientId=str[0];
            ConfigName.getInstance().DevId=str[1];
        }
        //消息回调
        MQTT.get().callback=new IMessage() {
            @Override
            public void MessageRecive(String topic, String Message) {
                try {
                    if(!Message.isEmpty())
                    {

                        String msg=  new AES().Decrypt(Message);
                        if(!msg.isEmpty())
                        {
                            BPAPackage model=new Json<BPAPackage>().jsonToobject(BPAPackage.class,((String)msg));
                            if((model.ClientId+"").equals(ConfigName.getInstance().DevId) && model.ClientType==9)
                            {
                                MessageLog.ShowInfo("收到远程更新数据通知！");
                                RefreshTheData(model.Message);
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.d("1", "MessageRecive: ");
                }
            }
        };
        //连接成功标志
        MQTT.get().ConnectOk=new IRun() {
            @Override
            public void Run() {

                String[] Str={ConfigName.getInstance().mqtt_topic+ ConfigName.getInstance().ClientId};
                MQTT.get().Subscrib(Str);
                MessageLog.ShowInfo("订阅主题：" + Str);

            }
        };
        //初始化MQTT连接
        MQTT.get().Connect(ConfigName.getInstance().mqtt_userName,
                ConfigName.getInstance().mqtt_passWord,
                ConfigName.getInstance().mqtt_ip,
                ConfigName.getInstance().mqtt_post);
        //云端数据处理线程
//        ThreadManager.Get().StartLong("云订单接收处理", true, new IThread() {
//            @Override
//            public void Run() throws InterruptedException {
//                if(MQTT.get().IsConnect)
//                {
//                    while (Commoditys.size() > 0) {
//                        //1.取出订单
//                        ResReceiveOrder order = Commoditys.poll();
//                        if(order.order!=null && order.subOrder!=null)
//                        {
//                            QueryDB.AddOrder(order.order);
//                            for(BPA_SUBORDER suborder: order.subOrder)
//                            {
//                                QueryDB.AddSubOrder(suborder);
//                                //向订单执行队列增加子订单
//                                BusinessServer.Get().AddCommodity(suborder);
//                            }
//                        }
//                    }
//                }
//                Thread.sleep(2000);
//            }
//            @Override
//            public void RunComplete() throws InterruptedException {
//            }
//        });

        ThreadManager.Get().StartLong("心跳服务", true, new IThread() {
            @Override
            public void Run() throws InterruptedException {

                if(MQTT.get().IsConnect)
                {
                    try {
                        PushHeart();
                    } catch (Exception e) {

                    }
                }
                Thread.sleep(1000);
            }
            @Override
            public void RunComplete() throws InterruptedException {
            }
        });
    }

    public void PushHeart() throws Exception {
        BPA_HeartPackage heart=new BPA_HeartPackage();
        heart.MessageId=16;
        heart.ClientId=Integer.parseInt(ConfigName.getInstance().DevId);
        heart.ClientType=9;
        Message_HeartModel mode=new Message_HeartModel();
        mode.DeviceType=9;
        mode.Healthy=1;
        heart.Message=mode;
        heart.MessageVersion=0;
        heart.Timestamp=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String Message= new Json<BPA_HeartPackage>().objectToJson(BPA_HeartPackage.class,heart);
        String msg=  new AES().Encrypt(Message);

        MQTT.get().publish(ConfigName.getInstance().mqtt_hearttopic,msg);
    }
    /**
     * 刷新数据
     * @param data
     */
    public void RefreshTheData(PushDeviceGoods data)
    {
        try {
            //1.更新商品数据
            for (BPA_GOODS item:QueryDB.GetGoodsALL())
            {
                QueryDB.DeleteGoods(item);
            }
            int k=1;
            for (BPA_GoodsInfo item:data.GoodsInfos)
            {
               //if(!QueryDB.GetGoodsIDIs(item.Id))
               {
                   BPA_GOODS goodx = new BPA_GOODS();
                   goodx.id=item.Id;
                   goodx.name = item.Goods_Name;
                   goodx.sort = item.Goods_Sort==0?k: item.Goods_Sort;
                   goodx.status = item.Status==1?0:1;
                   goodx.url=item.Goods_ImgUrl;
                   goodx.deviceID = ConfigName.getInstance().DeviceId;
                   goodx.userID = ConfigName.getInstance().user.userID;
                   QueryDB.AddGoods(goodx);
               }
                k++;
            }

            //2.新增物料
            for (BPA_MATERIAL item:QueryDB.GetMaterialALL())
            {
                QueryDB.DeleteMaterial(item);
            }
            ConcurrentHashMap<String,BPA_MATERIAL> Info=new ConcurrentHashMap<>();
            List<BatchingsInfo> bayc=data.BatchingsInfos;
            Collections.sort(bayc, new Comparator<BatchingsInfo>() {
                @Override
                public int compare(BatchingsInfo o1, BatchingsInfo o2) {

                    return Double.valueOf(o1.BatchingKey).compareTo(Double.valueOf(o2.BatchingKey));
                }
            });
            Integer I=0;
            for (BatchingsInfo item:bayc)
            {
                BPA_MATERIAL bpa_material=new BPA_MATERIAL();
                bpa_material.id=item.BatchingId;
                bpa_material.name=item.BatchingName;
                bpa_material.imgUrl="";
                bpa_material.createTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new Date().getTime() + I*1000));;
                bpa_material.deviceID= ConfigName.getInstance().DeviceId;
                bpa_material.userID=ConfigName.getInstance().user.userID;
                if(!Info.containsKey(item.BatchingId))
                    Info.put(item.BatchingId,bpa_material);
                I++;
            }
            for (String item:Info.keySet())
            {
                QueryDB.AddMaterial(Info.get(item));
            }
            //3.新增商品配方关联表
            for (BPA_SILOSANDMATERIAL item:QueryDB.GetSilosAndMaterialALL())//删除料仓关联物料
            {
                BatchingsInfo info=null;
                for (BatchingsInfo wl:bayc)
                {
                    if (wl.BatchingId.equals(item.materialID))
                    {
                        info=wl;
                    }
                }

                if(info==null)
                {
                    item.materialID="";
                    QueryDB.UpdateSilosAndMaterial(item);
                }
            }
            for (BPA_GOODSRECIPE item:QueryDB.GetGoodsSrecipeALL())//删除商品配方明细
            {
                QueryDB.DeleteGoodsSrecipe(item);
            }

            if(data.TechnologyActions==null || data.TechnologyActions.size()<=0)
            {
                ConcurrentHashMap<String,Batchingstechnology> chnology=new ConcurrentHashMap<>();
                for(Batchingstechnology item:data.Batchingstechnologys)
                {
                    if(!Info.containsKey(item.BomentryId))
                        chnology.put(item.BomentryId,item);
                }

                for(GoodsBom item:data.GoodsBomInfos)
                {
                    BPA_GOODSRECIPE da=new BPA_GOODSRECIPE();
                    da.goodsID = item.GoodsId;
                    da.exp=item.BomName;
                    da.materialType =1;
                    da.deviceID = ConfigName.getInstance().DeviceId;
                    da.userID = ConfigName.getInstance().user.userID;
                    for (BatchingsInfo info: data.BatchingsInfos)
                    {
                        if(info.GoodsBomId.equals(item.GoodsBomId))
                        {
                            da.id=info.Id;
                            Batchingstechnology gy= chnology.get(info.Id);
                            da.materialID = info.BatchingId;
                            da.value = (int)info.BomQty;
                            if(gy!=null)
                            {
                                da.sort =gy.Sort;
                            }
                            QueryDB.AddGoodsSrecipe(da);
                        }
                    }
                }
            }else
            {
                for (TechnologyActions actions:data.TechnologyActions)
                {
                    GoodsBom bom=null;
                    for(GoodsBom item:data.GoodsBomInfos)
                    {
                        if(item.BomId.equals(actions.BomId))
                        {
                            bom=item;
                        }
                    }
                    if(bom!=null)
                    {
                        BPA_GOODSRECIPE da=new BPA_GOODSRECIPE();
                        da.goodsID = bom.GoodsId;
                        da.exp=bom.BomName;
                        da.materialType =1;
                        da.deviceID = ConfigName.getInstance().DeviceId;
                        da.userID = ConfigName.getInstance().user.userID;
                        if(!actions.ActionJson.isEmpty())
                        {
                            List<GyAction> gyActions=  new Json<List<GyAction>>().jsonToListobject(GyAction.class,((String)actions.ActionJson));
                            for (GyAction a:gyActions)
                            {
                                da.id=java.util.UUID.randomUUID().toString();
                                da.materialID = a.BatchingId;
                                da.value = a.ActionValue;
                                da.sort =Integer.parseInt(actions.Sort);
                                QueryDB.AddGoodsSrecipe(da);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.d("TAG", "RefreshTheData: ");
        }
    }
    //endregion
}
