package com.bonait.bnframework.HttpModel;

import com.alibaba.fastjson.TypeReference;
import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.API.APIHelper;
import com.bonait.bnframework.HBL.API.APIResultT;
import com.bonait.bnframework.HBL.API.Utils;
import com.bonait.bnframework.MainApplication;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.file.DBHelper;
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_PLCADDRESS;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;

public class APIService {
    private static List<DeviceGoodInfo> deviceGoodInfo = new ArrayList<DeviceGoodInfo>();
    private static MaterialData materialModels = new MaterialData();
    public static List<DeviceGoodInfo> GetGoodInfo(){
        return deviceGoodInfo;
    }
    public static MaterialData GetMaterialModels(){ return materialModels; }
    private static long lastTime = System.currentTimeMillis();

    public static void MainInit(){
        Utils.disableSSLCertChecking();
        CleanData();
        GetMaterialInfo();
//        GetGoodsInfo();
    }

    private static void GetGoodsInfo(){
       String autoKey = ConfigName.getInstance().DeviceAutoKey;
        String url = "https://cfv.black-pa.com/kitchbase/api/goods/Getdevicegoods?deviceId="+autoKey;
        long curTime = System.currentTimeMillis();
        LogUtils.d(" GetGoodsInfo1 usetime="+(curTime-lastTime));
        lastTime = curTime;
        APIHelper.PostT(url,null,null,new TypeReference<APIResultT<GoodsData>>(){}).OnSource(s->{
            long curTime2 = System.currentTimeMillis();
            LogUtils.d(" GetGoodsInfo11 usetime="+(curTime2-lastTime));
            lastTime = curTime2;
            if(s.Content!=null){
                deviceGoodInfo=s.Content.getGoodsInfoList();
            }
            UpdateLocalGoodsInfo();
        });
        curTime = System.currentTimeMillis();
        LogUtils.d(" GetGoodsInfo2 usetime="+(curTime-lastTime));
        lastTime = curTime;
    }

    private static void GetMaterialInfo(){
        String url = "https://cfv.black-pa.com/saasbase/api/ExternalPlatform/Material/GetMaterialPageList";
        String key ="2c39bc05-25c2-46c4-b5c6-dba349058492";
        long curTime = System.currentTimeMillis();
        LogUtils.d(" GetMaterialInfo1 usetime="+(curTime-lastTime));
        lastTime = curTime;
        APIHelper.PostT(url,new MaterialRequestPar(1,100),key,new TypeReference<APIResultT<MaterialData>>(){}).OnSource(s->{
            long curTime2 = System.currentTimeMillis();
            LogUtils.d(" GetMaterialInfo11 usetime="+(curTime2-lastTime));
            lastTime = curTime2;
            materialModels=s.Content;
            UpdateLocalMaterial();
        });
        curTime = System.currentTimeMillis();
        LogUtils.d(" GetMaterialInfo2 usetime="+(curTime-lastTime));
        lastTime = curTime;
    }

    private static void CleanData(){
        long curTime = System.currentTimeMillis();
        LogUtils.d(" CleanData1 usetime="+(curTime-lastTime));
        lastTime = curTime;

        DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_MATERIAL.class,"id");
        DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODS.class,null);
        DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODSRECIPE.class,null);
        DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODSTYPE.class,null);
        DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODPROPERTY.class,null);
        DBHelper.getInstance(MainApplication.getContext()).DeleteCreateTables(BPA_GOODSRECIPENAME.class,null);

//        List<BPA_MATERIAL> materials =  QueryDB.GetMaterialALL();
//        materials.forEach(data->{QueryDB.DeleteMaterial(data);});

//        List<BPA_GOODS> goods =  QueryDB.GetGoodsALL();//获取所有商品
//        goods.forEach(data->{QueryDB.DeleteGoods(data);});
//
//        List<BPA_GOODSRECIPE> goodSrecipes=  QueryDB.GetGoodsSrecipeALL();
//        goodSrecipes.forEach(data->{QueryDB.DeleteGoodsSrecipe(data);});
//
//        List<BPA_GOODSTYPE> goodTypes =  QueryDB.GetGoodsTypeALL();//获取所有商品分类
//        goodTypes.forEach(data->{QueryDB.DeleteGoodsType(data);});
//
//        List<BPA_GOODPROPERTY> goodProperties =  QueryDB.GetGoodsSubPropertyALL();//获取所有规格
//        goodProperties.forEach(data->{ QueryDB.DeleteGoodsProperty(data);});
//
//        List<BPA_GOODSRECIPENAME> goodReciepeNames =  QueryDB.GetGoodsSrecipeNameALL();//获取所有配方信息
//        goodReciepeNames.forEach(data->{QueryDB.DeleteGoodsRecipeName(data);});
        curTime = System.currentTimeMillis();
        LogUtils.d(" CleanData2 usetime="+(curTime-lastTime));
        lastTime = curTime;
    }

    private static void UpdateLocalMaterial(){
        long curTime = System.currentTimeMillis();
        LogUtils.d(" UpdateLocalMaterial1 usetime="+(curTime-lastTime));
        lastTime = curTime;
        List<BPA_MATERIAL> datas = new ArrayList<>();
        materialModels.data.forEach(item->{
            if(item.name!=null){
                BPA_MATERIAL bpa_material =new BPA_MATERIAL();
                bpa_material.name = item.name;
                bpa_material.id = item.id;
                datas.add(bpa_material);
            }
        });
        QueryDB.AddMaterialList(datas);

        LogUtils.d(" UpdateLocalMaterial2 usetime="+(curTime-lastTime));
        lastTime = curTime;
        GetGoodsInfo();
    }

    private static void UpdateLocalGoodsInfo(){
        long curTime = System.currentTimeMillis();
        LogUtils.d(" UpdateLocalGoodsInfo1 usetime="+(curTime-lastTime));
        lastTime = curTime;
//        List<BPA_GOODS> goods =  QueryDB.GetGoodsALL();//获取所有商品
//        List<BPA_GOODSTYPE> goodTypes =  QueryDB.GetGoodsTypeALL();//获取所有商品分类
//        List<BPA_GOODPROPERTY> goodProperties =  QueryDB.GetGoodsPropertyALL();//获取所有规格
//        List<BPA_GOODSRECIPENAME> goodReciepeNames =  QueryDB.GetGoodsSrecipeNameALL();//获取所有配方信息
        GoodTypeSynchronous();
        GoodPropSynchronous();//同步云端商品属性
        GoodInfoSynchronous();//同步云端商品信息
        GoodRecipeSynchronous();

        curTime = System.currentTimeMillis();
        LogUtils.d(" UpdateLocalGoodsInfo3 usetime="+(curTime-lastTime));
        lastTime = curTime;
    }

    /**
     * 同步云端商品分类到本地
     */
    private static void GoodTypeSynchronous(){
        LogUtils.d("GoodTypeSynchronous1");
        List<BPA_GOODSTYPE> datas = new ArrayList<>();
        for(DeviceGoodInfo item : deviceGoodInfo){
            BPA_GOODSTYPE bpa_goodstype = new BPA_GOODSTYPE();
            bpa_goodstype.name = item.goodsTypeName;
            bpa_goodstype.id = item.goodsTypeId;
            bpa_goodstype.userID="超级管理员";
            datas.add(bpa_goodstype);
        }
        QueryDB.AddGoodsTypeList(datas);
    }

    /**
     * 同步云端商品属性到本地
     */
    private static void GoodPropSynchronous(){
        LogUtils.d("GoodPropSynchronous");
        List<BPA_GOODPROPERTY> datas = new ArrayList<>();
        for(DeviceGoodInfo item : deviceGoodInfo){
            if(item.goodsAttributeList!=null){
                for(int n=0;n<item.goodsAttributeList.size();n++){
                    //属性添加
                    BPA_GOODPROPERTY bpa_goodproperty = new BPA_GOODPROPERTY();
                    bpa_goodproperty.name = item.goodsAttributeList.get(n).goodsAttributeName;
                    bpa_goodproperty.parentid ="0";
                    bpa_goodproperty.sort =n+1;
                    bpa_goodproperty.id = item.goodsAttributeList.get(n).goodsAttributeId;
                    bpa_goodproperty.userID="超级管理员";
                    bpa_goodproperty.GoodsTypeId=item.goodsTypeId;
                    datas.add(bpa_goodproperty);

                    //子属性添加
                    if(item.goodsAttributeList.get(n).goodsAttributeValueList!=null){
                        for(int i=0;i<item.goodsAttributeList.get(n).goodsAttributeValueList.size();i++){
                            BPA_GOODPROPERTY bpa_goodpropertySub = new BPA_GOODPROPERTY();
                            bpa_goodpropertySub.name = item.goodsAttributeList.get(n).goodsAttributeValueList.get(i).attributeValue;
                            bpa_goodpropertySub.parentid = item.goodsAttributeList.get(n).goodsAttributeId;
                            bpa_goodpropertySub.id = item.goodsAttributeList.get(n).goodsAttributeValueList.get(i).goodsAttributeValueId;
                            bpa_goodpropertySub.sort = i+1;
                            bpa_goodpropertySub.userID="超级管理员";
                            datas.add(bpa_goodpropertySub);
                        }
                    }
                }
            }

        }
        QueryDB.AddGoodsPropertyList(datas);
    }

    /**
     * 同步云端商品信息到本地
     */
    private static void GoodInfoSynchronous(){
        LogUtils.d("GoodInfoSynchronous");
        List<BPA_GOODS> datas = new ArrayList<>();
        for(DeviceGoodInfo item : deviceGoodInfo){
            if(item.goodsInfoList!=null){
                for(int i=0;i<item.goodsInfoList.size();i++){
                    BPA_GOODS bpa_goods =new BPA_GOODS();
                    bpa_goods.id = item.goodsInfoList.get(i).goodsId;
                    bpa_goods.name = item.goodsInfoList.get(i).goodsName;
                    bpa_goods.materialids = getMaterialids(item.goodsInfoList.get(i));
                    bpa_goods.goodtype=item.goodsTypeId;
                    bpa_goods.status=1;
                    bpa_goods.issc=1;
                    bpa_goods.maketime = 180;
                    bpa_goods.url=item.goodsInfoList.get(i).imgUrl==null?"":item.goodsInfoList.get(i).imgUrl;
                    bpa_goods.sort= i+1;
                    bpa_goods.foreignKeyRe="";
                    datas.add(bpa_goods);
                }
            }
        }
        QueryDB.AddGoodsList(datas);

    }

    /**
     * 获取商品工艺物料组合
     * @param goodinfo
     * @return
     */
    private static String getMaterialids(GoodsInfoList goodinfo){
        StringBuffer materialSB = new StringBuffer();
        List<BPA_MATERIAL> bpaMaterials  =  QueryDB.GetMaterialALL();
        goodinfo.goodsTechnologyActionList.forEach(material->{
            material.GetFuncModel().OnSource(action->{
                FuncModel func=  action.Content.stream().filter(p->p.actionName.equals("主料名称")).findFirst().get();
                BPA_MATERIAL bpaMaterial=  bpaMaterials.stream().filter(p->p.name.equals(func.actionValue)).findFirst().get();
                materialSB.append(bpaMaterial.id).append(",");
            });
        });
        if(materialSB.toString().length()<=0)return "";
        return materialSB.toString().substring(0,materialSB.length()-1);
    }

    /**
     * 同步云端配方详细信息到本地
     */
    private static void GoodRecipeSynchronous() {
        LogUtils.d("GoodRecipeSynchronous");
        List<BPA_GOODSRECIPENAME> datas1 = new ArrayList<>();
        List<BPA_GOODSRECIPE> datas2 = new ArrayList<>();
        for(DeviceGoodInfo item : deviceGoodInfo){
            if(item.goodsInfoList!=null){
                List<BPA_GOODPROPERTY> goodProps = QueryDB.GetGoodsSubPropertyALL();
                List<BPA_MATERIAL> bpaMaterials  =  QueryDB.GetMaterialALL();
                item.goodsInfoList.forEach(goodinfo->{
                    try {
                        ConcurrentHashMap<String,List<GoodsTechnologyActionList>> recipes = new ConcurrentHashMap<>();
                        goodinfo.goodsTechnologyActionList.forEach(material->{
                            if(!recipes.containsKey(material.goodsAttributeId))recipes.put(material.goodsAttributeId,new ArrayList<>());
                            recipes.get(material.goodsAttributeId).add(material);
                        });

                        recipes.forEach((key,value)->{
                            //添加配方
                            BPA_GOODSRECIPENAME bpa_goodsrecipename = new BPA_GOODSRECIPENAME();
                            bpa_goodsrecipename.name =GetRecipeName(goodinfo.goodsName, value.get(0).goodsAttributeId,goodProps);
                            bpa_goodsrecipename.goodsID= goodinfo.goodsId;
                            bpa_goodsrecipename.design=key;
                            datas1.add(bpa_goodsrecipename);

                            //遍历工艺步骤
                            value.forEach(material->{
                                material.GetFuncModel().OnSource(action->{
                                    FuncModel func=  action.Content.stream().filter(p->p.actionName.equals("主料名称")).findFirst().get();
                                    BPA_MATERIAL bpaMaterial=  bpaMaterials.stream().filter(p->p.name.equals(func.actionValue)).findFirst().get();
                                    FuncModel weight=  action.Content.stream().filter(p->p.actionName.equals("主料重量")).findFirst().get();
                                    FuncModel sort=  action.Content.stream().filter(p->p.actionName.equals("执行步骤")).findFirst().get();
                                    if(bpaMaterial!=null){
                                        BPA_GOODSRECIPE bpa_goodsrecipe = new BPA_GOODSRECIPE();
                                        bpa_goodsrecipe.goodsID = goodinfo.goodsId;
                                        bpa_goodsrecipe.materialID = bpaMaterial.id;
                                        bpa_goodsrecipe.value =weight.actionValue;
                                        bpa_goodsrecipe.sort = Integer.parseInt(sort.actionValue);
                                        bpa_goodsrecipe.recipeID=bpa_goodsrecipename.id;
                                        datas2.add(bpa_goodsrecipe);
                                    }
                                });
                            });
                        });
                    }catch (Exception e){
                        LogUtils.d("GoodRecipeSynchronous 5"+goodinfo.goodsId);
                        e.printStackTrace();
                    }

                });
            }
        }
        LogUtils.d("GoodRecipeSynchronous6");
        QueryDB.AddGoodsRecipeNameList(datas1);
        LogUtils.d("GoodRecipeSynchronous7");
        QueryDB.AddGoodsSrecipeList(datas2);
        LogUtils.d("GoodRecipeSynchronous8");
    }

    /**
     * 获取子商品名称
     * @param goodsName
     * @param goodsAttributeId
     * @param goodProps
     * @return
     */
    private static String GetRecipeName(String goodsName,String goodsAttributeId, List<BPA_GOODPROPERTY> goodProps){
        String[] props = goodsAttributeId.split("[,]");
        StringBuffer recpipeNameTemp = new StringBuffer();
        recpipeNameTemp.append(goodsName).append("_");
        try{
            for(int i=0;i<props.length;i++){
                String id = props[i];
                BPA_GOODPROPERTY tempGoodProp = goodProps.stream().filter(p->p.id.equals(id)).findFirst().get();
                if(tempGoodProp!=null)  recpipeNameTemp.append(tempGoodProp.name).append("_") ;
            }
        }catch (Exception e){
            LogUtils.d(" GetRecipeName goodsAttributeId="+goodsAttributeId);
        }


        return recpipeNameTemp.toString().substring(0, recpipeNameTemp.length() - 1);
    }

}
