package com.bonait.bnframework.business;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_CLOUDDATA;
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_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.db.mode.BPA_SYSTEMSET;
import com.bonait.bnframework.common.db.mode.Res_PLCADDRESS;
import com.bonait.bnframework.common.helper.ConfigUtil;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IRunT;
import com.bonait.bnframework.common.helper.Json;
import com.bonait.bnframework.common.http.callback.json.JsonDialogCallback;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.modbus.ModbusTcpHelper;
import com.bonait.bnframework.common.modbus.ModbusTcpMainHelper;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.model.ResAPI;
import com.bonait.bnframework.common.model.mode.ActionJsonMode;
import com.bonait.bnframework.common.model.mode.BPA_GoodsAttributeValue;
import com.bonait.bnframework.common.model.mode.BPA_GoodsTechnologyAction;
import com.bonait.bnframework.common.model.mode.BomTechnologyActionInfo;
import com.bonait.bnframework.common.model.mode.BomTypeInfo;
import com.bonait.bnframework.common.model.mode.ProcessT;
import com.bonait.bnframework.common.model.mode.ResGoodProcess;
import com.bonait.bnframework.common.model.mode.TechnologyValueMode;
import com.bonait.bnframework.common.model.mode.BatchingInfo;
import com.bonait.bnframework.common.model.mode.CloudGood;
import com.bonait.bnframework.common.model.mode.DeviceInformation;
import com.bonait.bnframework.common.model.mode.FoodMenuInfo;
import com.bonait.bnframework.common.model.mode.GoodsParentTypeInfo;
import com.bonait.bnframework.common.model.mode.GoodsTechnology;
import com.bonait.bnframework.common.model.mode.GoodsTypeInfo;
import com.bonait.bnframework.common.model.mode.GoodsUintInfo;
import com.bonait.bnframework.common.model.mode.OrganizeMode;
import com.bonait.bnframework.common.model.mode.ResALLData;
import com.bonait.bnframework.common.model.mode.TechnologyAction;
import com.bonait.bnframework.common.model.mode.UpdateBomInfo;
import com.bonait.bnframework.common.model.mode.UpdateCloudGood;
import com.bonait.bnframework.common.oss.OssHelper;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.GoodEditDialog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * 主函数进程
 * 主要进行配置文件-系统类
 */
public class ConfigData {
    //region 私有
    private static ConfigData mInstance; //实例变量设置私有，防止直接通过类名访问

    public static synchronized ConfigData getInstance() { //静态同步方法作为唯一的实例对象获取方式
        if (mInstance == null) {
            mInstance = new ConfigData();
        }
        return mInstance;
    }

    private ConfigData() { //默认构造函数私有，防止类外直接new创建对象
        Init();
    }
    //endregion

    //region 外部调用事件

    /**
     * 初始化
     */
    public void Init() {
        //1.加载系统设置
        LoadSystem();
        ToggleEnvironment();
        //2.加载配置
        LoadingPZ();
        //3.初始化业务
        //4.初始化日志上报adad
    }

    /**
     * 加载系统配置
     */
    public void LoadSystem() {
        ArrayList<BPA_SYSTEMSET> bpa_systemsets = QueryDB.GetSystemsetALL();
//        for(BPA_SYSTEMSET item:bpa_systemsets)
//        {
//            QueryDB.DeleteSystemset(item.id);
//        }
        for (int i = 1; i < 5; i++) {
            int ty = i;
            BPA_SYSTEMSET set = new BPA_SYSTEMSET();
            set.type = ty;
            switch (ty) {
                case 1:
                    set.value = ConfigName.getInstance().Address;
                    break;
                case 2:
                    set.value = String.valueOf(ConfigName.getInstance().Post);
                    break;
                case 3:
                    set.value = ConfigName.getInstance().ClientAutoKey;
                    break;
                case 4:
                    set.value = ConfigName.getInstance().DeviceAutoKey;
                    break;
            }
            set.deviceID = ConfigName.getInstance().DeviceId;
            set.userID = ConfigName.getInstance().user.userID;
            BPA_SYSTEMSET find = null;
            for (BPA_SYSTEMSET item : bpa_systemsets) {
                if (item.type == ty) {
                    find = item;
                    break;
                }
            }
            if (find == null) {
                QueryDB.AddSystemset(set);
            }
        }

        BPA_SYSTEMSET find_99 = null;
        BPA_SYSTEMSET find_100 = null;
        BPA_SYSTEMSET find_200 = null;
        BPA_SYSTEMSET find_201 = null;
        BPA_SYSTEMSET find_202 = null;

        for (BPA_SYSTEMSET item : bpa_systemsets) {
            if (item.type == -99) {
                find_99 = item;
            } else if (item.type == -100) {
                find_100 = item;
            }else if (item.type == -200) {
                find_200 = item;
            }else if (item.type == -201) {
                find_201 = item;
            }else if (item.type == -202) {
                find_202 = item;
            }
        }
        if (find_99 == null) {
            BPA_SYSTEMSET set = new BPA_SYSTEMSET();
            set.type = -99;
            set.value = ConfigName.getInstance().Environment;
            set.deviceID = ConfigName.getInstance().DeviceId;
            set.userID = ConfigName.getInstance().user.userID;
            QueryDB.AddSystemset(set);
        }
        if (find_100 == null) {
            BPA_SYSTEMSET set = new BPA_SYSTEMSET();
            set.type = -100;
            set.value = ConfigName.getInstance().versionSelectionEnum;
            set.deviceID = ConfigName.getInstance().DeviceId;
            set.userID = ConfigName.getInstance().user.userID;
            QueryDB.AddSystemset(set);
        }

        if (find_200 == null) {
            BPA_SYSTEMSET set = new BPA_SYSTEMSET();
            set.type = -200;
            set.value = ConfigName.getInstance().MainAddress;
            set.deviceID = ConfigName.getInstance().DeviceId;
            set.userID = ConfigName.getInstance().user.userID;
            QueryDB.AddSystemset(set);
        }

        if (find_201 == null) {
            BPA_SYSTEMSET set = new BPA_SYSTEMSET();
            set.type = -201;
            set.value = String.valueOf(ConfigName.getInstance().MainPost);
            set.deviceID = ConfigName.getInstance().DeviceId;
            set.userID = ConfigName.getInstance().user.userID;
            QueryDB.AddSystemset(set);
        }

        if (find_202 == null) {
            BPA_SYSTEMSET set = new BPA_SYSTEMSET();
            set.type = -202;
            set.value = String.valueOf(ConfigName.getInstance().DeviceHao);
            set.deviceID = ConfigName.getInstance().DeviceId;
            set.userID = ConfigName.getInstance().user.userID;
            QueryDB.AddSystemset(set);
        }


        bpa_systemsets = QueryDB.GetSystemsetALL();
        for (BPA_SYSTEMSET item : bpa_systemsets) {
            switch (item.type) {
                case -100:
                    ConfigName.getInstance().versionSelectionEnum = item.value;
                    break;
                case -99:
                    ConfigName.getInstance().Environment = item.value;
                    break;
                case -200:
                    ConfigName.getInstance().MainAddress = item.value;
                    break;
                case -201:
                    ConfigName.getInstance().MainPost = Integer.parseInt(item.value);
                    break;
                case -202:
                    ConfigName.getInstance().DeviceHao = Integer.parseInt(item.value);
                    break;
                case 1:
                    ConfigName.getInstance().Address = item.value;
                    break;
                case 2:
                    ConfigName.getInstance().Post = Integer.parseInt(item.value);
                    break;
                case 3:
                    ConfigName.getInstance().ClientAutoKey = item.value;
                    break;
                case 4:
                    ConfigName.getInstance().DeviceAutoKey = item.value;
                    break;
            }

        }
    }

    /**
     * 切换环境
     */
    public void ToggleEnvironment() {
        if (ConfigName.getInstance().Environment.equals("开发环境")) {
            ConfigName.getInstance().SaasAddress = "https://bpa.black-pa.com:21527/";
            ConfigName.getInstance().mqtt_userName = "emqx_u_block";
            ConfigName.getInstance().mqtt_passWord = "emqx_p_admin8765490789";
            ConfigName.getInstance().mqtt_ip = "10.2.1.21";
            ConfigName.getInstance().mqtt_post = 1883;
        } else if (ConfigName.getInstance().Environment.equals("测试环境")) {
            ConfigName.getInstance().SaasAddress = "https://bpa.black-pa.com:21528/";
            ConfigName.getInstance().mqtt_userName = "emqx_u_block";
            ConfigName.getInstance().mqtt_passWord = "emqx_p_admin8456765490789";
            ConfigName.getInstance().mqtt_ip = "111.9.47.105";
            ConfigName.getInstance().mqtt_post = 18889;
        } else if (ConfigName.getInstance().Environment.equals("正式环境")) {
            ConfigName.getInstance().SaasAddress = "https://witt.black-pa.com/";
            ConfigName.getInstance().mqtt_userName = "emqx_u_block";
            ConfigName.getInstance().mqtt_passWord = "emqx_p_admin3658765490789";
            ConfigName.getInstance().mqtt_ip = "47.108.65.220";
            ConfigName.getInstance().mqtt_post = 1883;
        }
    }

    /**
     * 加载配置
     */
    public void LoadingPZ() {
        //1.店铺配置
//        ConfigName.getInstance().Shop_Name = ConfigUtil.read(ConfigName.getInstance().dishesCon, "Shop_Name", ConfigName.getInstance().Shop_Name);
//        ConfigName.getInstance().AutKey = ConfigUtil.read(ConfigName.getInstance().dishesCon, "AutKey", ConfigName.getInstance().AutKey);
        //2.用户名称
        ConfigName.getInstance().user.account = ConfigUtil.read(ConfigName.getInstance().dishesCon, "username", ConfigName.getInstance().user.account);
        ConfigName.getInstance().user.pass = ConfigUtil.read(ConfigName.getInstance().dishesCon, "password", ConfigName.getInstance().user.pass);
        ConfigName.getInstance().IsUserDownOrder = ConfigUtil.read(ConfigName.getInstance().dishesCon, "IsUserDownOrder", ConfigName.getInstance().IsUserDownOrder);
        ConfigName.getInstance().Version = ConfigUtil.read(ConfigName.getInstance().dishesCon, "Version", ConfigName.getInstance().Version);
        ConfigName.getInstance().HuoLi = ConfigUtil.read(ConfigName.getInstance().dishesCon, "HuoLi", ConfigName.getInstance().HuoLi);
        ConfigName.getInstance().MaxTemp = ConfigUtil.read(ConfigName.getInstance().dishesCon, "MaxTemp", ConfigName.getInstance().MaxTemp);
        ConfigName.getInstance().WhetherManualFeedingSuspended = ConfigUtil.read(ConfigName.getInstance().dishesCon, "WhetherManualFeedingSuspended", ConfigName.getInstance().WhetherManualFeedingSuspended);


        ConfigName.getInstance().gkcxCount          = ConfigUtil.read(ConfigName.getInstance().dishesCon, "gkcxCount", ConfigName.getInstance().gkcxCount          );
        ConfigName.getInstance().jiaobanCount       = ConfigUtil.read(ConfigName.getInstance().dishesCon, "jiaobanCount", ConfigName.getInstance().jiaobanCount       );
        ConfigName.getInstance().qingxiCount        = ConfigUtil.read(ConfigName.getInstance().dishesCon, "qingxiCount", ConfigName.getInstance().qingxiCount        );
        ConfigName.getInstance().touliaoCount       = ConfigUtil.read(ConfigName.getInstance().dishesCon, "touliaoCount", ConfigName.getInstance().touliaoCount       );
        ConfigName.getInstance().yetiliaoCount      = ConfigUtil.read(ConfigName.getInstance().dishesCon, "yetiliaoCount", ConfigName.getInstance().yetiliaoCount      );
        ConfigName.getInstance().yanchiCount        = ConfigUtil.read(ConfigName.getInstance().dishesCon, "yanchiCount", ConfigName.getInstance().yanchiCount        );
        ConfigName.getInstance().jiareCount         = ConfigUtil.read(ConfigName.getInstance().dishesCon, "jiareCount", ConfigName.getInstance().jiareCount         );
        ConfigName.getInstance().jiarewendingCount  = ConfigUtil.read(ConfigName.getInstance().dishesCon, "jiarewendingCount", ConfigName.getInstance().jiarewendingCount  );
        ConfigName.getInstance().RunCount           = ConfigUtil.read(ConfigName.getInstance().dishesCon, "RunCount", ConfigName.getInstance().RunCount           );

        ConfigName.getInstance().AutoCCTime           = ConfigUtil.read(ConfigName.getInstance().dishesCon, "AutoCCTime", ConfigName.getInstance().AutoCCTime           );
        ConfigName.getInstance().AutoQXTime           = ConfigUtil.read(ConfigName.getInstance().dishesCon, "AutoQXTime", ConfigName.getInstance().AutoQXTime           );

    }

    /**
     * 保存配置
     */
    public void SavePZ() {
        //1.店铺配置
//        ConfigUtil.write(ConfigName.getInstance().dishesCon,"Shop_Name", ConfigName.getInstance().Shop_Name);
//        ConfigUtil.write(ConfigName.getInstance().dishesCon,"AutKey", ConfigName.getInstance().AutKey);
        //2.用户信息
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "username", ConfigName.getInstance().user.account);
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "password", ConfigName.getInstance().user.pass);
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "IsUserDownOrder", ConfigName.getInstance().IsUserDownOrder);
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "Version", ConfigName.getInstance().Version);
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "HuoLi", ConfigName.getInstance().HuoLi);
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "MaxTemp", ConfigName.getInstance().MaxTemp);
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "WhetherManualFeedingSuspended", ConfigName.getInstance().WhetherManualFeedingSuspended);


        ConfigUtil.write(ConfigName.getInstance().dishesCon, "gkcxCount",       ConfigName.getInstance().gkcxCount          );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "jiaobanCount", ConfigName.getInstance().jiaobanCount       );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "qingxiCount", ConfigName.getInstance().qingxiCount        );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "touliaoCount", ConfigName.getInstance().touliaoCount       );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "yetiliaoCount", ConfigName.getInstance().yetiliaoCount      );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "yanchiCount", ConfigName.getInstance().yanchiCount        );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "jiareCount", ConfigName.getInstance().jiareCount         );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "jiarewendingCount", ConfigName.getInstance().jiarewendingCount  );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "RunCount", ConfigName.getInstance().RunCount           );


        ConfigUtil.write(ConfigName.getInstance().dishesCon, "AutoCCTime", ConfigName.getInstance().AutoCCTime           );
        ConfigUtil.write(ConfigName.getInstance().dishesCon, "AutoQXTime", ConfigName.getInstance().AutoQXTime           );

    }

    /**
     * 加载云端数据
     */
    public void LoadingCloud() {
        ArrayList<BPA_CLOUDDATA> data = QueryDB.GetClouddataALL();
        if (data.size() > 0) {
            ConfigName.getInstance().cloudData = new ResALLData();
            for (BPA_CLOUDDATA item : data) {
                if (item.name.equals("物料集合")) {
                    ConfigName.getInstance().cloudData.batchingInfo = new Json<BatchingInfo>().jsonToListobject(BatchingInfo.class, item.text);
                } else if (item.name.equals("工艺模型")) {
                    ConfigName.getInstance().cloudData.goodsTechnology = new Json<GoodsTechnology>().jsonToListobject(GoodsTechnology.class, item.text);
                } else if (item.name.equals("工艺模型详细信息")) {
                    ConfigName.getInstance().cloudData.technologyAction = new Json<TechnologyAction>().jsonToListobject(TechnologyAction.class, item.text);
                } else if (item.name.equals("菜谱信息")) {
                    ConfigName.getInstance().cloudData.foodMenuInfo = new Json<FoodMenuInfo>().jsonToListobject(FoodMenuInfo.class, item.text);
                } else if (item.name.equals("商品小类")) {
                    ConfigName.getInstance().cloudData.goodsTypeInfo = new Json<GoodsTypeInfo>().jsonToListobject(GoodsTypeInfo.class, item.text);
                } else if (item.name.equals("商品大类")) {
                    ConfigName.getInstance().cloudData.goodsParentTypeInfo = new Json<GoodsParentTypeInfo>().jsonToListobject(GoodsParentTypeInfo.class, item.text);
                } else if (item.name.equals("商品单位")) {
                    ConfigName.getInstance().cloudData.goodsUintInfo = new Json<GoodsUintInfo>().jsonToListobject(GoodsUintInfo.class, item.text);
                } else if (item.name.equals("配方分类")) {
                    ConfigName.getInstance().cloudData.bomTypeInfo = new Json<BomTypeInfo>().jsonToListobject(BomTypeInfo.class, item.text);
                } else if (item.name.equals("商品属性")) {
                    ConfigName.getInstance().cloudData.goodsAttributeValue = new Json<BomTypeInfo>().jsonToListobject(BPA_GoodsAttributeValue.class, item.text);
                }
            }
        }
    }

    /**
     * 获取组织信息
     *
     * @param context
     */
    public void GetOrganize(Context context) {
        if (NetworkUtils.checkNetworkAvailable(context)) {
            //获取店铺信息
            OkGo.<ResAPI<OrganizeMode>>get(ConfigName.getInstance().SaasAddress + ConfigName.getInstance().GetStore + ConfigName.getInstance().ClientAutoKey)
                    .tag(context)
                    .execute(new JsonDialogCallback<ResAPI<OrganizeMode>>(context) {
                        @Override
                        public void onSuccess(Response<ResAPI<OrganizeMode>> response) {
                            ResAPI<OrganizeMode> organize = response.body();
                            if (organize.isSuccess) {
                                ConfigName.getInstance().organizeMode = organize.data;
                                OkGo.<ResAPI<DeviceInformation>>get(String.format(ConfigName.getInstance().SaasAddress + ConfigName.getInstance().GetDeviceInformation, ConfigName.getInstance().organizeMode.id, ConfigName.getInstance().DeviceAutoKey)).tag(context).headers(new HttpHeaders("TenantId", ConfigName.getInstance().organizeMode.companyId)).execute(new JsonDialogCallback<ResAPI<DeviceInformation>>(context) {
                                    @Override
                                    public void onSuccess(Response<ResAPI<DeviceInformation>> response) {
                                        ResAPI<DeviceInformation> deviceInformation = response.body();
                                        if (deviceInformation.succeeded) {
                                            ConfigName.getInstance().deviceInformation = deviceInformation.data;
                                            if (ConfigName.getInstance().deviceInformation != null) {
                                                ConfigName.getInstance().DeviceId = ConfigName.getInstance().deviceInformation.id;
                                                MessageManager.getInstance().sendMessage(MessageName.GetOrganize, "GetOrganize");
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    });
        } else {
            ToastUtils.warning("无网络,请先连接网络!!!");
        }
    }

    /**
     * 同步云端数据
     */
    public void SyncDataInTheCloud(Context context, Handler mHandler) {
        if (NetworkUtils.checkNetworkAvailable(context)) {
            //region 拉取物料数据
            if (ConfigName.getInstance().organizeMode == null) {
                return;
            }
            OkGo.<ResAPI<ResALLData>>get(String.format(ConfigName.getInstance().SaasAddress + ConfigName.getInstance().GetBaseDataModel, ConfigName.getInstance().organizeMode.id, ConfigName.getInstance().DeviceAutoKey)).tag(context).headers(new HttpHeaders("TenantId", ConfigName.getInstance().organizeMode.companyId)).execute(new JsonDialogCallback<ResAPI<ResALLData>>(context) {
                @Override
                public void onSuccess(Response<ResAPI<ResALLData>> response) {
                    ResAPI<ResALLData> allDataResAPI = response.body();
                    if (allDataResAPI.succeeded && allDataResAPI.data != null) {
                        BPA_CLOUDDATA data = new BPA_CLOUDDATA();
                        ConfigName.getInstance().cloudData = allDataResAPI.data;
                        ArrayList<BPA_CLOUDDATA> arrayList = QueryDB.GetClouddataALL();
                        for (BPA_CLOUDDATA item : arrayList) {
                            QueryDB.DeleteClouddata(item);
                        }

                        //region 物料管理
                        List<BatchingInfo> bayc = allDataResAPI.data.batchingInfo;
                        if (allDataResAPI.data.batchingInfo != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "物料集合";
                            data.text = new Gson().toJson(bayc);
                            QueryDB.AddClouddata(data);

                            ArrayList<BPA_MATERIAL> materials = QueryDB.GetMaterialALL();
                            for (BPA_MATERIAL wl : materials) {
                                QueryDB.DeleteMaterial(wl);
                            }

                            Integer I = 0;
                            for (BatchingInfo item : bayc) {
                                BPA_MATERIAL bpa_material = new BPA_MATERIAL();
                                bpa_material.id = item.id;
                                bpa_material.name = item.batching_Name;
                                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;
                                QueryDB.AddMaterial(bpa_material);
                                I++;
                            }
                        }
                        //endregion

                        //region 工艺模型
                        if (allDataResAPI.data.goodsTechnology != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "工艺模型";
                            data.text = new Gson().toJson(allDataResAPI.data.goodsTechnology);
                            QueryDB.AddClouddata(data);

                            ArrayList<BPA_PROCESS> processes = QueryDB.GetProcessALL();
                            for (BPA_PROCESS pro : processes) {
                                QueryDB.DeleteProcess(pro);
                            }
                            Integer I = 0;
                            for (GoodsTechnology item : allDataResAPI.data.goodsTechnology) {
                                BPA_PROCESS bpa_process = new BPA_PROCESS();
                                bpa_process.id = item.id;
                                bpa_process.name = item.name;
                                bpa_process.createTime = item.createAt;
                                bpa_process.sort = I;
                                QueryDB.AddProcess(bpa_process);
                                I++;
                            }
                        }
                        //endregion

                        //region 工艺模型详细信息
                        if (allDataResAPI.data.technologyAction != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "工艺模型详细信息";
                            data.text = new Gson().toJson(allDataResAPI.data.technologyAction);
                            QueryDB.AddClouddata(data);

                            ArrayList<BPA_PROCESSModel> processes = QueryDB.GetProcessModelALL();
                            for (BPA_PROCESSModel pro : processes) {
                                QueryDB.DeleteProcessModel(pro);
                            }
                            for (TechnologyAction item : allDataResAPI.data.technologyAction) {
                                BPA_PROCESSModel bpa_process = new BPA_PROCESSModel();
                                bpa_process.id = item.id;
                                bpa_process.processid = item.goodstechnologyId;
                                bpa_process.name = item.actionName;
                                bpa_process.createTime = item.createAt;
                                bpa_process.sort = item.sort;
                                bpa_process.datatype = (item.actionType.equals("digit") ? 0 : ((item.actionType.equals("text") || item.actionType.equals("textarea") || item.actionType.equals("switch")) ? 1 : 2));
                                bpa_process.data = "";
                                if (item.actionType.equals("select") && !item.actionValue.isEmpty()) {
                                    List<TechnologyValueMode> val = new Json<TechnologyValueMode>().jsonToListobject(TechnologyValueMode.class, item.actionValue);
                                    for (int i = 0; i < val.size(); i++) {
                                        if (i < val.size() - 1) {
                                            bpa_process.data += val.get(i).actionValueName + "、";
                                        } else {
                                            bpa_process.data += val.get(i).actionValueName;
                                        }
                                    }
                                }
                                QueryDB.AddProcessModel(bpa_process);
                            }
                        }
                        //endegion


                        if (allDataResAPI.data.foodMenuInfo != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "菜谱信息";
                            data.text = new Gson().toJson(allDataResAPI.data.foodMenuInfo);
                            QueryDB.AddClouddata(data);
                        }

                        if (allDataResAPI.data.goodsTypeInfo != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "商品小类";
                            data.text = new Gson().toJson(allDataResAPI.data.goodsTypeInfo);
                            QueryDB.AddClouddata(data);
                        }

                        if (allDataResAPI.data.goodsParentTypeInfo != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "商品大类";
                            data.text = new Gson().toJson(allDataResAPI.data.goodsParentTypeInfo);
                            QueryDB.AddClouddata(data);
                        }

                        if (allDataResAPI.data.goodsUintInfo != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "商品单位";
                            data.text = new Gson().toJson(allDataResAPI.data.goodsUintInfo);
                            QueryDB.AddClouddata(data);
                        }

                        if (allDataResAPI.data.bomTypeInfo != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "配方分类";
                            data.text = new Gson().toJson(allDataResAPI.data.bomTypeInfo);
                            QueryDB.AddClouddata(data);
                        }

                        if (allDataResAPI.data.goodsAttributeValue != null) {
                            data = new BPA_CLOUDDATA();
                            data.id = java.util.UUID.randomUUID().toString();
                            data.name = "商品属性";
                            data.text = new Gson().toJson(allDataResAPI.data.goodsAttributeValue);
                            QueryDB.AddClouddata(data);
                        }

                        Message msg = new Message();
                        msg.obj = "MSG_REFRESH";
                        mHandler.sendMessage(msg);
                    }
                }
            });
            //endregion
        } else {
            ToastUtils.warning("无网络,请先连接网络!!!");
        }
    }

    /**
     * 获取设备所有商品信息
     *
     * @param context
     */
    public void GetGevGood(Context context, Handler mHandler) {
        if (NetworkUtils.checkNetworkAvailable(context)) {
            if (ConfigName.getInstance().organizeMode == null) {
                return;
            }
            OkGo.<ResAPI<List<CloudGood>>>get(String.format(ConfigName.getInstance().SaasAddress + ConfigName.getInstance().GetGoods, ConfigName.getInstance().organizeMode.id, ConfigName.getInstance().DeviceId)).tag(context).headers(new HttpHeaders("TenantId", ConfigName.getInstance().organizeMode.companyId)).execute(new JsonDialogCallback<ResAPI<List<CloudGood>>>(context) {
                @Override
                public void onSuccess(Response<ResAPI<List<CloudGood>>> response) {
                    ResAPI<List<CloudGood>> allDataResAPI = response.body();
                    if (allDataResAPI.succeeded && allDataResAPI.data != null && allDataResAPI.data.size() > 0) {
                        ConfigName.getInstance().cloudGoods = allDataResAPI.data;
                        if (mHandler != null) {
                            Message msg = new Message();
                            msg.obj = "MSG_REFRESH";
                            mHandler.sendMessage(msg);
                        }
                    }
                }
            });
        } else {
            ToastUtils.warning("无网络,请先连接网络!!!");
        }
    }

    /**
     * 获取商品配方信息
     *
     * @param context
     */
    public void GetGoodProcess(Context context, String goodid, Boolean isSX) {
        Boolean IsXZ = QueryDB.GetGoodsIDIs(goodid);
        if (IsXZ) {
            ToastUtils.warning("请勿重复下载,本地商品已存在!!!");
            return;
        }

        if (NetworkUtils.checkNetworkAvailable(context)) {
            if (ConfigName.getInstance().organizeMode == null) {
                return;
            }
            OkGo.<ResAPI<ResGoodProcess>>get(String.format(ConfigName.getInstance().SaasAddress + ConfigName.getInstance().GetGoodsBom, goodid, ConfigName.getInstance().DeviceId)).tag(context).headers(new HttpHeaders("TenantId", ConfigName.getInstance().organizeMode.companyId)).execute(new JsonDialogCallback<ResAPI<ResGoodProcess>>(context) {
                @Override
                public void onSuccess(Response<ResAPI<ResGoodProcess>> response) {
                    ResAPI<ResGoodProcess> allDataResAPI = response.body();
                    if (allDataResAPI.succeeded && allDataResAPI.data != null) {

                        CloudGood cloudGood = null;
                        for (CloudGood item : ConfigName.getInstance().cloudGoods) {
                            if (item.id.equals(goodid)) {
                                cloudGood = item;
                                break;
                            }
                        }

                        if (cloudGood != null) {
                            //1.增加商品
                            BPA_GOODS good = new BPA_GOODS();
                            good.id = cloudGood.id;
                            good.name = cloudGood.goods_Name;
                            good.status = 1;
                            good.sort = QueryDB.GetGoodsALL().size() + 1;
                            good.maketime = 180;
                            good.issc = 0;
                            good.url = cloudGood.goods_ImgUrl;
                            good.exp = "云端商品";
                            good.gyid="";
                            if(allDataResAPI.data.bomInfo!=null && allDataResAPI.data.bomInfo.size()>0)
                            {
                                good.gyid =allDataResAPI.data.bomInfo.get(0).id;
                            }

                            good.userID=cloudGood.goods_TypeID==null?"":cloudGood.goods_TypeID;
                            QueryDB.AddGoods(good);
                            //2.增加配方
//                            if (allDataResAPI.data.bomTechnologyActionInfo != null && allDataResAPI.data.bomTechnologyActionInfo.size() > 0) {
//                                List<BomTechnologyActionInfo> bayc = allDataResAPI.data.bomTechnologyActionInfo;
//                                Collections.sort(bayc, new Comparator<BomTechnologyActionInfo>() {
//                                    @Override
//                                    public int compare(BomTechnologyActionInfo o1, BomTechnologyActionInfo o2) {
//
//                                        return Double.valueOf(o1.sort).compareTo(Double.valueOf(o2.sort));
//                                    }
//                                });
//                                for (BomTechnologyActionInfo k : allDataResAPI.data.bomTechnologyActionInfo) {
//                                    BPA_GOODSRECIPE item = new BPA_GOODSRECIPE();
//                                    item.goodsID = good.id;
//                                    item.sort = k.sort;
//                                    if(k.stepName.contains("液体料"))
//                                    {
//                                        item.processname="液体料";
//                                    }else if(k.stepName.contains("搅拌"))
//                                    {
//                                        item.processname="搅拌";
//                                    }else if(k.stepName.contains("位置"))
//                                    {
//                                        item.processname="位置";
//                                    }else if(k.stepName.contains("加热"))
//                                    {
//                                        item.processname="加热";
//                                    }else if(k.stepName.contains("主料"))
//                                    {
//                                        item.processname="主料";
//                                    }else if(k.stepName.contains("延迟"))
//                                    {
//                                        item.processname="延迟";
//                                    }else if(k.stepName.contains("出菜"))
//                                    {
//                                        item.processname="出菜";
//                                    }else
//                                    {
//                                        item.processname = k.stepName;
//                                    }
//
//                                    if (!k.actionJson.isEmpty()) {
//                                        String data = "";
//                                        String desc = "";
//                                        boolean iswl = false;
//                                        List<ActionJsonMode> gyActions = new Json<List<ActionJsonMode>>().jsonToListobject(ActionJsonMode.class, ((String) k.actionJson));
//                                        for (ActionJsonMode m : gyActions) {
//                                            if(m.ActionName!=null && m.ActionValue!="")
//                                            {
//                                                data += m.ActionName + "," + m.ActionValue + "|";
//                                                desc += m.ActionValue + ",";
//                                                if (!m.BatchingId.isEmpty()) {
//                                                    iswl = true;
//                                                }
//                                            }
//                                        }
//                                        if (data.contains("|")) {
//                                            item.processvalue = data.substring(0, data.length() - 1);
//                                        }
//                                        if (desc.contains(",")) {
//                                            item.processms = item.processname + "(" + desc.substring(0, desc.length() - 1) + ")";
//                                        }
//                                        item.materialType = iswl ? 0 : 1;
//                                    }
//                                    QueryDB.AddGoodsSrecipe(item);
//                                }
//                            }

                            if (allDataResAPI.data.goodsTechnologyActionInfo != null && allDataResAPI.data.goodsTechnologyActionInfo.size() > 0) {
                                List<BPA_GoodsTechnologyAction> bayc = allDataResAPI.data.goodsTechnologyActionInfo;
                                Collections.sort(bayc, new Comparator<BPA_GoodsTechnologyAction>() {
                                    @Override
                                    public int compare(BPA_GoodsTechnologyAction o1, BPA_GoodsTechnologyAction o2) {

                                        return Double.valueOf(o1.sort).compareTo(Double.valueOf(o2.sort));
                                    }
                                });
                                for (BPA_GoodsTechnologyAction k : allDataResAPI.data.goodsTechnologyActionInfo) {
                                    BPA_GOODSRECIPE item = new BPA_GOODSRECIPE();
                                    item.goodsID = good.id;
                                    item.sort = k.sort;
                                    if (k.stepName.contains("液体料")) {
                                        item.processname = "液体料";
                                    } else if (k.stepName.contains("搅拌")) {
                                        item.processname = "搅拌";
                                    } else if (k.stepName.contains("位置")) {
                                        item.processname = "位置";
                                    } else if (k.stepName.contains("加热")) {
                                        item.processname = "加热";
                                    } else if (k.stepName.contains("主料")) {
                                        item.processname = "主料";
                                    } else if (k.stepName.contains("延迟")) {
                                        item.processname = "延迟";
                                    } else if (k.stepName.contains("出菜")) {
                                        item.processname = "出菜";
                                    } else {
                                        item.processname = k.stepName;
                                    }

                                    if (!k.actionJson.isEmpty()) {
                                        String data = "";
                                        String desc = "";
                                        //boolean iswl = false;
                                        List<ActionJsonMode> gyActions = new Json<List<ActionJsonMode>>().jsonToListobject(ActionJsonMode.class, ((String) k.actionJson));
                                        for (ActionJsonMode m : gyActions) {
                                            if (m.actionName != null && m.actionValue != "") {
                                                data += m.actionName + "," + m.actionValue + "|";
                                                desc += m.actionValue + ",";
//                                                if (!m.batchingId.isEmpty()) {
//                                                    iswl = true;
//                                                }
                                            }
                                        }
                                        if (data.contains("|")) {
                                            item.processvalue = data.substring(0, data.length() - 1);
                                        }
                                        if (desc.contains(",")) {
                                            item.processms = item.processname + "(" + desc.substring(0, desc.length() - 1) + ")";
                                        }
                                        item.materialType =k.isBatch ? 1 : 0;
                                    }
                                    QueryDB.AddGoodsSrecipe(item);
                                }
                            }
                            ToastUtils.info("下载菜品成功!!!");

                            if (isSX) {
                                MessageManager.getInstance().sendMessage(MessageName.ScGood, "Good");
                            }
                        }
                    }
                }
            });
        } else {
            ToastUtils.warning("无网络,请先连接网络!!!");
        }

    }

    /**
     * 上传商品信息
     *
     * @param context
     * @param goodid
     */
    public void UploadGoods(Context context, String goodid) {
        try {
            if (NetworkUtils.checkNetworkAvailable(context)) {
                if (ConfigName.getInstance().organizeMode == null && ConfigName.getInstance().cloudData != null) {
                    ToastUtils.warning("无组织信息不能上传,请设置当前店铺信息!!!");
                    return;
                }
                BPA_GOODS good = QueryDB.GetGoodsId(goodid);//ConfigName.getInstance().SaasAddress
                OkGo.<ResAPI<List<CloudGood>>>get(String.format(ConfigName.getInstance().SaasAddress + ConfigName.getInstance().GetGoodIsCloud, good.name))
                        .tag(context)
                        .tag(context).headers(new HttpHeaders("TenantId", ConfigName.getInstance().organizeMode.companyId))
                        .execute(new JsonDialogCallback<ResAPI<List<CloudGood>>>(context) {
                            @Override
                            public void onSuccess(Response<ResAPI<List<CloudGood>>> response) {
                                ResAPI<List<CloudGood>> organize = response.body();
                                //商品配方
                                if (organize.data.isEmpty()) {

                                } else {
                                    CloudGood good_p= organize.data.get(0);
                                    if(!good.id.equals(good_p.id)) //如果商品id 不一致 需要删除商品并且新建商品
                                    {
                                        QueryDB.DeleteGoods(good);

                                        ArrayList<BPA_GOODSRECIPE> goodsrecipes1 = QueryDB.GetGoodsSrecipeID(good.id);
                                        for (BPA_GOODSRECIPE k:goodsrecipes1)
                                        {
                                            QueryDB.DeleteGoodsSrecipe(k);
                                            k.goodsID=good_p.id;
                                            QueryDB.AddGoodsSrecipe(k);
                                        }

                                        good.id =good_p.id;
                                        QueryDB.AddGoods(good);
                                    }

                                    //创建商品bom清单
                                    if(good.gyid == null && good_p.goodsBomInfo!=null && good_p.goodsBomInfo.size()>0)
                                    {
                                        good.gyid =good_p.goodsBomInfo.get(0).bomId;
                                        QueryDB.UpdateGoodsGY(good.id, good.gyid);
                                    }
                                }


                                final GoodEditDialog editDialog = new GoodEditDialog(context);
                                editDialog.setTitle("上传菜谱界面");
                                editDialog.setYesOnclickListener("确定", new GoodEditDialog.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick(String sp, String dl, String xl, String dw, String fl, String sxid) {

                                        Boolean isSuceess = false;
                                        try {
                                            final Boolean[] boom = {false};
                                            OssHelper.getInstance().OnCharge = new IRunT() {
                                                @Override
                                                public void Run(Object o) {
                                                    ResAPI<String> resAPI = (ResAPI<String>) o;
                                                    if (resAPI.succeeded) {
                                                        good.url = resAPI.data;
                                                        QueryDB.UpdateGoods(good);
                                                    }
                                                    boom[0] = true;
                                                }
                                            };
                                            if(good.url!=null)
                                            {
                                                OssHelper.getInstance().UpdataFile(context, good.url);
                                                while (!boom[0]) {
                                                    Thread.sleep(100);
                                                }
                                            }
                                        } catch (Exception ex) {

                                        }
                                        UpdateCloudGood update = new UpdateCloudGood();
                                        try {
                                            update.storeId = ConfigName.getInstance().organizeMode.id;
                                            update.deviceId = ConfigName.getInstance().DeviceId;
                                            update.userId = ConfigName.getInstance().user.name;
                                            update.goodsInfo = new CloudGood();
                                            update.bomTechnologyActionInfo = new ArrayList<BomTechnologyActionInfo>();
                                            update.goodsTechnologyActionInfo = new ArrayList<BPA_GoodsTechnologyAction>();

                                            update.goodsInfo.id = good.id;
                                            update.goodsInfo.createAt = good.createTime;
                                            update.goodsInfo.isDeleted = 0;
                                            update.goodsInfo.status = 0;
                                            update.goodsInfo.groupId = ConfigName.getInstance().organizeMode.companyId;
                                            update.goodsInfo.autoKey = 0;
                                            update.goodsInfo.isWeigh = false;
                                            update.goodsInfo.vipPrice = 0;
                                            update.goodsInfo.price = 0;
                                            update.goodsInfo.code = good.id;
                                            update.goodsInfo.goods_Sort = good.sort;
                                            update.goodsInfo.goods_Descritption = "设备上传商品";
                                            update.goodsInfo.goods_Name = good.name;

                                            //选择菜谱 大类id 小类id 单位id
                                            update.foodMenuId = sp;
                                            update.goodsInfo.goods_ImgUrl = good.url;//图片地址
                                            update.goodsInfo.parentTypeID = dl;//大类
                                            update.goodsInfo.goods_TypeID = xl;//小类
                                            update.goodsInfo.goodsUintId = dw;//单位

                                            String id = good.gyid;
                                            if (good.gyid == null) {
                                                id = java.util.UUID.randomUUID().toString();
                                                QueryDB.UpdateGoodsGY(good.id, id);
                                            }
                                            QueryDB.UpdateGoodsTypeId(good.id,xl);

                                            UpdateBomInfo bom = new UpdateBomInfo();
                                            bom.id = id;
                                            bom.bomType = fl;
                                            bom.name = good.name;
                                            bom.code = java.util.UUID.randomUUID().toString();
                                            bom.isMain = true;
                                            bom.sort = 0;
                                            update.bomInfo = bom;

                                            ArrayList<BPA_GOODSRECIPE> goodsrecipes = QueryDB.GetGoodsSrecipeID(good.id);
                                            for (BPA_GOODSRECIPE item : goodsrecipes) {
                                                GoodsTechnology goodsTechnology = null;
                                                for (GoodsTechnology _find : ConfigName.getInstance().cloudData.goodsTechnology) {
                                                    if (_find.name.equals(item.processname)) {
                                                        goodsTechnology = _find;
                                                        break;
                                                    }
                                                }

                                                if (goodsTechnology != null) {
                                                    //2.根据工序变量集合-获取变量名称和值
                                                    List<String> names = new ArrayList<>();
                                                    final HashMap<String, String> formulation = new HashMap<>();
                                                    //region 获取变量名称和值
                                                    String text = item.processvalue;
                                                    List<String> data = new ArrayList<>();
                                                    if (text.contains("|")) {
                                                        String[] res = text.split("[|]");
                                                        for (int i = 0; i < res.length; i++) {
                                                            data.add(res[i]);
                                                        }
                                                    } else {
                                                        data.add(text);
                                                    }
                                                    for (String item1 : data) {
                                                        if (!item1.isEmpty() && item1.contains(",")) {
                                                            String[] wl = item1.split("[,]");
                                                            if (wl != null && wl.length == 2) {
                                                                String name = wl[0];
                                                                String val = wl[1];
                                                                names.add(name);
                                                                formulation.put(name, val);
                                                            }
                                                        }
                                                    }
                                                    //endregion

                                                    List<ActionJsonMode> actionJsonModes = new ArrayList<>();
                                                    //region 获取工艺集合
                                                    if (item.materialType == 0)//物料
                                                    {
                                                        for (String f : names) {
                                                            BatchingInfo batchingInfo = null;
                                                            for (BatchingInfo _find : ConfigName.getInstance().cloudData.batchingInfo) {
                                                                if (_find.batching_Name.equals(f)) {
                                                                    batchingInfo = _find;
                                                                    break;
                                                                }
                                                            }
                                                            ActionJsonMode m = new ActionJsonMode();
                                                            m.technologyactionId = batchingInfo != null ? batchingInfo.id :"";//模型id
                                                            m.batchingId =  "";//物料id
                                                            m.actionName = f;
                                                            m.actionValue = formulation.get(f);
                                                            actionJsonModes.add(m);
                                                        }
                                                    } else//模型
                                                    {
                                                        for (String f : names) {
                                                            TechnologyAction technologyAction = null;
                                                            for (TechnologyAction _find : ConfigName.getInstance().cloudData.technologyAction) {
                                                                if (_find.actionName.equals(f) && _find.goodstechnologyId.equals(goodsTechnology.id)) {
                                                                    technologyAction = _find;
                                                                    break;
                                                                }
                                                            }
                                                            ActionJsonMode m = new ActionJsonMode();
                                                            m.technologyactionId = technologyAction != null ? technologyAction.id : "";//模型id
                                                            m.batchingId = "";//物料id
                                                            m.actionName = f;
                                                            m.actionValue = formulation.get(f);
                                                            actionJsonModes.add(m);
                                                        }
                                                    }
                                                    //endregion

//                                    BomTechnologyActionInfo info = new BomTechnologyActionInfo();
//                                    info.stepName = item.processname;
//                                    info.actionJson = new Gson().toJson(actionJsonModes);
//                                    info.isBatch = (item.materialType == 0 ? true : false);
//                                    info.chnologyId = goodsTechnology.id;//工艺名称id
//                                    info.createAt = item.createTime;
//                                    info.groupId = ConfigName.getInstance().organizeMode.companyId;
//                                    info.id = item.id;
//                                    info.isDeleted = 0;
//                                    info.sort = item.sort;
//                                    info.bomId=bom.id;
//                                    update.bomTechnologyActionInfo.add(info);

                                                    BPA_GoodsTechnologyAction info2 = new BPA_GoodsTechnologyAction();
                                                    info2.stepName = item.processname;
                                                    info2.actionJson = new Gson().toJson(actionJsonModes);
                                                    info2.isBatch = (item.materialType == 0 ? false:true);
                                                    info2.chnologyId = goodsTechnology.id;//工艺名称id
                                                    info2.createAt = item.createTime;
                                                    info2.groupId = ConfigName.getInstance().organizeMode.companyId;
                                                    info2.id = item.id;
                                                    info2.isDeleted = 0;
                                                    info2.sort = item.sort;
                                                    info2.goodsId = good.id;
                                                    info2.deviceId = ConfigName.getInstance().DeviceId;
                                                    info2.goodsAttributeId = sxid;
                                                    update.goodsTechnologyActionInfo.add(info2);
                                                }
                                            }
                                            isSuceess = true;
                                        } catch (Exception ex) {
                                            isSuceess = true;
                                            ToastUtils.info("上传菜品异常:" + ex.getMessage());
                                        }


                                        if (isSuceess) {
                                            try {
                                                String str = ConfigName.getInstance().SaasAddress + ConfigName.getInstance().UpdateGoods;
                                               // String str="http://192.168.1.7:5000/api/CommInteface/SendGoodsInfo";
                                                OkGo.<ResAPI<Boolean>>post(str).tag(context).upRequestBody(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(update))).headers(new HttpHeaders("TenantId", ConfigName.getInstance().organizeMode.companyId)).execute(new JsonDialogCallback<ResAPI<Boolean>>(context) {
                                                    @Override
                                                    public void onSuccess(Response<ResAPI<Boolean>> response) {
                                                        ResAPI<Boolean> allDataResAPI = response.body();
                                                        if (allDataResAPI.succeeded) {
                                                            ToastUtils.info("上传菜品成功!!!");
                                                            MessageManager.getInstance().sendMessage(MessageName.ScGood, "GoodUpdate");
                                                            editDialog.dismiss();
                                                        } else {
                                                            ToastUtils.warning("上传菜品失败!!!");
                                                        }
                                                    }
                                                });
                                            } catch (Exception ex) {
                                                ToastUtils.info("上传菜品异常:" + ex.getMessage());
                                            }
                                        }
                                    }
                                });
                                editDialog.setNoOnclickListener("取消", new GoodEditDialog.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        editDialog.dismiss();
                                    }
                                });
                                editDialog.show();
                            }
                        });


            } else {
                ToastUtils.warning("无网络,请先连接网络!!!");
            }
        } catch (Exception ex) {
        }
    }

    /**
     * 增加本地图片
     */
    public void AddImage(Context context) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 2;//宽高压缩为原来的1/2
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image1, options);
        Bitmap bitmap2 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image2, options);
        Bitmap bitmap3 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image3, options);
        Bitmap bitmap4 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image4, options);
        Bitmap bitmap5 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image5, options);
        Bitmap bitmap6 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image6, options);
        Bitmap bitmap7 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.loading123, options);

        LocalCacheUtils localCacheUtils = new LocalCacheUtils();
        localCacheUtils.setBitmapToLocal("image1.png", bitmap1);
        localCacheUtils.setBitmapToLocal("image2.png", bitmap2);
        localCacheUtils.setBitmapToLocal("image3.png", bitmap3);
        localCacheUtils.setBitmapToLocal("image4.png", bitmap4);
        localCacheUtils.setBitmapToLocal("image5.png", bitmap5);
        localCacheUtils.setBitmapToLocal("image6.png", bitmap6);
        localCacheUtils.setBitmapToLocal("loading123.png", bitmap7);


    }

    /**
     * 恢复plc地址
     */
    public void RevertPLC() {
        try {
            List<Res_PLCADDRESS> plcaddresses = ConfigName.getInstance().PlcAddress_大炒;
            List<ProcessT> processTS = ConfigName.getInstance().Process_大炒;

            if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_大炒;
                processTS = ConfigName.getInstance().Process_大炒;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("大炒自动投料版本")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_大炒自动投料;
                processTS = ConfigName.getInstance().Process_大炒自动投料;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("小炒版本")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_小炒;
                processTS = ConfigName.getInstance().Process_小炒;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("一拖四大炒")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_一拖四;
                processTS = ConfigName.getInstance().Process_一拖四;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("一拖二大炒")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_大炒自动投料;
                processTS = ConfigName.getInstance().Process_一拖四;
            }

            //region 恢复PLC
            ArrayList<BPA_PLCADDRESS> arrayList = QueryDB.GetPlcaddressALL();
            for (BPA_PLCADDRESS item : arrayList) {
                QueryDB.DeletePlcaddress(item);
            }
            int k = 1;
            for (Res_PLCADDRESS item : plcaddresses) {
                BPA_PLCADDRESS plc = new BPA_PLCADDRESS();
                plc.name = item.name;
                plc.address = item.address;
                plc.isread = item.isread;
                plc.iswrite = item.iswrite;
                plc.sort = k;
                k++;
                QueryDB.AddPlcaddress(plc);
            }
            //endregion
        } catch (Exception ex) {

        }
    }
    /**
     * 恢复出厂设置 PLC与工序
     */
    public void RevertPLCProcess() {
        try {
            List<Res_PLCADDRESS> plcaddresses = ConfigName.getInstance().PlcAddress_大炒;
            List<ProcessT> processTS = ConfigName.getInstance().Process_大炒;

            if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_大炒;
                processTS = ConfigName.getInstance().Process_大炒;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("大炒自动投料版本")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_大炒自动投料;
                processTS = ConfigName.getInstance().Process_大炒自动投料;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("小炒版本")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_小炒;
                processTS = ConfigName.getInstance().Process_小炒;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("一拖四大炒")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_一拖四;
                processTS = ConfigName.getInstance().Process_一拖四;
            } else if (ConfigName.getInstance().versionSelectionEnum.equals("一拖二大炒")) {
                plcaddresses = ConfigName.getInstance().PlcAddress_大炒自动投料;
                processTS = ConfigName.getInstance().Process_一拖四;
            }

            //region 恢复PLC
            ArrayList<BPA_PLCADDRESS> arrayList = QueryDB.GetPlcaddressALL();
            for (BPA_PLCADDRESS item : arrayList) {
                QueryDB.DeletePlcaddress(item);
            }
            int k = 1;
            for (Res_PLCADDRESS item : plcaddresses) {
                BPA_PLCADDRESS plc = new BPA_PLCADDRESS();
                plc.name = item.name;
                plc.address = item.address;
                plc.isread = item.isread;
                plc.iswrite = item.iswrite;
                plc.sort = k;
                k++;
                QueryDB.AddPlcaddress(plc);
            }
            //endregion

            //region 恢复工序
            ArrayList<BPA_PROCESS> a = QueryDB.GetProcessALL();
            for (BPA_PROCESS item : a) {
                ArrayList<BPA_PROCESSModel> arrayList1 = QueryDB.GetProcessModelALL();
                for (BPA_PROCESSModel item1 : arrayList1) {
                    QueryDB.DeleteProcessModel(item1);
                }
                QueryDB.DeleteProcess(item);
            }
            int index = 1;
            for (ProcessT key : processTS) {
                List<String> values = key.val;
                BPA_PROCESS process = new BPA_PROCESS();
                process.sort = index;
                process.name = key.name;
                QueryDB.AddProcess(process);//增加模型
                int chidindex = 1;
                for (String item : values)//模型
                {
                    BPA_PROCESSModel processModel = new BPA_PROCESSModel();
                    processModel.processid = process.id;
                    processModel.name = item;
                    processModel.sort = chidindex;
                    processModel.data = ConfigName.getInstance().GetProcessTypeVal(item);
                    processModel.datatype = ((item.contains("名称") ? 1 : (processModel.data.isEmpty() ? 0 : 2)));
                    QueryDB.AddProcessModel(processModel);
                    chidindex++;
                }
                index++;
            }
            //endregion

        } catch (Exception ex) {

        }
    }
    //endregion

    //region PLC初始化
    /**
     * 关闭PLC
     */
    public void ColsePLC() {
        ModbusTcpHelper.get().release();//释放modbus
        ConfigName.getInstance().PlcIsConnect = false;

        if(ConfigName.getInstance().versionSelectionEnum.contains("一拖"))
        {
            ModbusTcpMainHelper.get().release();//释放modbus
            ConfigName.getInstance().PlcMainIsConnect = false;
        }
    }

    /**
     * PLC初始化完成时,需要注册的服务
     */
    public void PLC_Init() {
        //PLC连接成功，启动数据监听
        ExecuteTheRecipe.Listening();
    }

    /**
     * PLC主控初始化完成时,需要注册的服务
     */
    public void MainPLC_Init() {
        //PLC连接成功，启动数据监听
        ExecuteTheRecipe.MainListening();
    }
    //endregion
}

