package com.bonait.bnframework.business;

import android.util.Log;

import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODPROPERTY;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPENAME;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_MENU;
import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL;
import com.bonait.bnframework.common.helper.AES;
import com.bonait.bnframework.common.helper.I.IMessage;
import com.bonait.bnframework.common.helper.Json;
import com.bonait.bnframework.common.helper.MQTT;
import com.bonait.bnframework.common.helper.mode.BPAPackage;
import com.bonait.bnframework.common.helper.mode.BPA_GoodsInfo;
import com.bonait.bnframework.common.helper.mode.BPA_HeartPackage;
import com.bonait.bnframework.common.helper.mode.BatchingsInfo;
import com.bonait.bnframework.common.helper.mode.Batchingstechnology;
import com.bonait.bnframework.common.helper.mode.BomAttributeValueReInfo;
import com.bonait.bnframework.common.helper.mode.GoodsAttributeInfo;
import com.bonait.bnframework.common.helper.mode.GoodsAttributeValueInfo;
import com.bonait.bnframework.common.helper.mode.GoodsBom;
import com.bonait.bnframework.common.helper.mode.GyAction;
import com.bonait.bnframework.common.helper.mode.Message_HeartModel;
import com.bonait.bnframework.common.helper.mode.PushDeviceGoods;
import com.bonait.bnframework.common.helper.mode.TechnologyActions;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
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 公共函数
    /**
     * 初始化
     */
    public void Init()
    {
    }

    /**
     * MQTT初始化
     */
    public void MqttInit()
    {
        //消息回调
        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())
                        {
                            Log.d("远程数据更新", msg);
                            BPAPackage model=new Json<BPAPackage>().jsonToobject(BPAPackage.class,((String)msg));
                            if((model.ClientId+"").equals(ConfigName.getInstance().DeviceAutoKey) && 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().ClientAutoKey};
                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,()->{
            if(MQTT.get().IsConnect){
                PushHeart();
            }
            Thread.sleep(1000);
        });
    }

    public void PushHeart() throws Exception {
        BPA_HeartPackage heart=new BPA_HeartPackage();
        heart.MessageId=16;
        heart.ClientId=Integer.parseInt(ConfigName.getInstance().DeviceAutoKey);
        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 {
            //region 更新商品类型
            List<String> GoodType=new ArrayList<>();
            for (BPA_GOODSTYPE item: QueryDB.GetGoodsTypeALL())
            {
                QueryDB.DeleteGoodsType(item);
            }
            for (BPA_GoodsInfo item:data.GoodsInfos)
            {
                if(!GoodType.contains(item.Goods_TypeID))
                {
                    BPA_GOODSTYPE bpa_goodstype = new BPA_GOODSTYPE();
                    bpa_goodstype.id=item.TypeId;
                    bpa_goodstype.name =item.Goods_TypeID;
                    bpa_goodstype.deviceID = ConfigName.getInstance().DeviceId;
                    bpa_goodstype.userID = ConfigName.getInstance().user.userID;
                    QueryDB.AddGoodsType(bpa_goodstype);
                }
                GoodType.add(item.Goods_TypeID);
            }
            //endregion

            //region 更新规格属性
            for (BPA_GOODPROPERTY item: QueryDB.GetGoodsPropertyALL("0"))
            {
                ArrayList<BPA_GOODPROPERTY> ddd=QueryDB.GetGoodsPropertyALL(item.id);
                for (BPA_GOODPROPERTY item1:ddd)
                {
                    QueryDB.DeleteGoodsProperty(item1);
                }
                QueryDB.DeleteGoodsProperty(item);
            }

            for (GoodsAttributeInfo info :data.GoodsAttributeInfo)
            {
                BPA_GOODPROPERTY bpa_goodproperty = new BPA_GOODPROPERTY();
                bpa_goodproperty.id=info.Id;
                bpa_goodproperty.name = info.AttributeName;
                bpa_goodproperty.foreignKeyRe = "";
                bpa_goodproperty.parentid = "0";
                bpa_goodproperty.GoodsTypeId=info.GoodsTypeId;
                bpa_goodproperty.sort=info.Sort;
                bpa_goodproperty.deviceID = ConfigName.getInstance().DeviceId;
                bpa_goodproperty.userID = ConfigName.getInstance().user.userID;
                QueryDB.AddGoodsProperty(bpa_goodproperty);
                for (GoodsAttributeValueInfo val: info.GoodsAttributeValue)
                {
                    bpa_goodproperty.id=val.Id;
                    bpa_goodproperty.name = val.AttributeValue;
                    bpa_goodproperty.foreignKeyRe = val.WaiKey;
                    bpa_goodproperty.parentid = info.Id;
                    bpa_goodproperty.GoodsTypeId="";
                    bpa_goodproperty.sort=val.Sort;
                    bpa_goodproperty.deviceID = ConfigName.getInstance().DeviceId;
                    bpa_goodproperty.userID = ConfigName.getInstance().user.userID;
                    QueryDB.AddGoodsProperty(bpa_goodproperty);
                }
            }
            //endregion

            //region 更新商品数据
            for (BPA_GOODS item:QueryDB.GetGoodsALL())
            {
                QueryDB.DeleteGoods(item);
            }

            int k=1;
            for (BPA_GoodsInfo item:data.GoodsInfos)
            {
                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.maketime = 180;
                goodx.issc = 1;
                goodx.status = item.Status==1?0:1;
                goodx.url=item.Goods_ImgUrl;
                goodx.deviceID = ConfigName.getInstance().DeviceId;
                goodx.userID = ConfigName.getInstance().user.userID;
                goodx.foreignKeyRe=item.ForeignKeyRe;
                goodx.goodtype=item.TypeId;
                goodx.materialids=item.DefaultMate;
                QueryDB.AddGoods(goodx);
                k++;
            }
            //endregion

            //region 更新物料数据,料仓物料绑定关系
            for (BPA_MATERIAL item:QueryDB.GetMaterialALL())
            {
                QueryDB.DeleteMaterial(item);
            }

            //物料id / 物料数据
            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.type=0;
                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));
            }

            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);
                }
            }
            //endregion

            //region 更新商品配方 配方信息
            for (BPA_GOODSRECIPENAME item:QueryDB.GetGoodsSrecipeNameALL())//商品配方表
            {
                QueryDB.DeleteGoodsRecipeName(item);
            }
            for (BPA_GOODSRECIPE item:QueryDB.GetGoodsSrecipeALL())//删除商品配方明细
            {
                QueryDB.DeleteGoodsSrecipe(item);
            }


            ConcurrentHashMap<String, BomAttributeValueReInfo> bomAttributeValueReInfo=new ConcurrentHashMap<>();
            for (BomAttributeValueReInfo item:data.BomAttributeValueReInfo)//商品配方关联表
            {
                if(!Info.containsKey(item.GoodsId+","+item.BoomId))
                {
                    bomAttributeValueReInfo.put(item.GoodsId+","+item.BoomId,item);
                }
            }

            for (GoodsBom item:data.GoodsBomInfos)//商品配方信息
            {
                BPA_GOODSRECIPENAME n=new BPA_GOODSRECIPENAME();
                n.id=item.GoodsBomId;
                n.name=item.BomName;
                n.goodsID=item.GoodsId;
                BomAttributeValueReInfo km=bomAttributeValueReInfo.get(item.GoodsId+","+item.BomId);
                if(km!=null)
                {
                    n.design=km.GoodsAttributeValueId;
                }
                QueryDB.AddGoodsRecipeName(n);


                BPA_GOODSRECIPE da=new BPA_GOODSRECIPE();
                da.goodsID = item.GoodsId;
                da.exp=item.BomName;
                da.materialType =1;
                da.recipeID=item.GoodsBomId;
                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;
                        da.materialID = info.BatchingId;
                        da.value =String.format ("%.1f", info.BomQty);
                        da.sort =0;
                        QueryDB.AddGoodsSrecipe(da);
                    }
                }
            }
            //endregion
        } catch (Exception e) {
            Log.d("TAG", "RefreshTheData: ");
        }
    }
    //endregion
}
