package com.bonait.bnframework.HttpModel;

import com.alibaba.fastjson.TypeReference;
import com.bonait.bnframework.HBL.API.APIHelper;
import com.bonait.bnframework.HBL.API.APIResultT;
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 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; }

    public static void MainInit(){
        CleanData();
        GetMaterialInfo();
        GetGoodsInfo();
    }

    private static void GetGoodsInfo(){
        String url = "http://192.168.1.50:5007/api/goods/Getdevicegoods?deviceId=1a2a1d72-752f-44cf-87f8-ec9fe4ea15b8";
        APIHelper.PostT(url,null,null,new TypeReference<APIResultT<List<DeviceGoodInfo>>>(){}).OnSource(s->{
            deviceGoodInfo=s.Content;
            UpdateLocalGoodsInfo();
        });
    }

    private static void GetMaterialInfo(){
        String url = "http://192.168.1.50:5006/api/ExternalPlatform/Material/GetMaterialPageList";
        String key ="962a5892-0f7f-47b4-a1ec-925bd7914a6d";
        APIHelper.PostT(url,new MaterialRequestPar(1,100),key,new TypeReference<APIResultT<MaterialData>>(){}).OnSource(s->{
            materialModels=s.Content;
            UpdateLocalMaterial();
        });
    }

    private static void CleanData(){
        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);});
    }

    private static void UpdateLocalMaterial(){
        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;
                QueryDB.AddMaterial(bpa_material);
            }
        });
    }

    private static void UpdateLocalGoodsInfo(){
        List<BPA_GOODS> goods =  QueryDB.GetGoodsALL();//获取所有商品
        List<BPA_GOODSTYPE> goodTypes =  QueryDB.GetGoodsTypeALL();//获取所有商品分类
        List<BPA_GOODPROPERTY> goodProperties =  QueryDB.GetGoodsPropertyALL();//获取所有规格
        List<BPA_GOODSRECIPENAME> goodReciepeNames =  QueryDB.GetGoodsSrecipeNameALL();//获取所有配方信息
        deviceGoodInfo.forEach(item->{

            GoodTypeSynchronous(item);//同步云端商品分类信息

            GoodPropSynchronous(item.goodsAttributeList);//同步云端商品属性

            GoodInfoSynchronous(item,goods);//同步云端商品信息

            GoodRecipeSynchronous(item,goodReciepeNames);
        });
    }

    /**
     * 同步云端商品分类到本地
     * @param item
     */
    private static void GoodTypeSynchronous(DeviceGoodInfo item){
        BPA_GOODSTYPE bpa_goodstype = new BPA_GOODSTYPE();
        bpa_goodstype.name = item.goodsTypeName;
        bpa_goodstype.id = item.goodsTypeId;
        bpa_goodstype.userID="超级管理员";
        QueryDB.AddGoodsType(bpa_goodstype);
    }

    /**
     * 同步云端商品属性到本地
     * @param goodsAttributeList
     */
    private static void GoodPropSynchronous( List<GoodsAttributeList> goodsAttributeList){
        goodsAttributeList.forEach(goodProperty->{
            //属性添加
            BPA_GOODPROPERTY bpa_goodproperty = new BPA_GOODPROPERTY();
            bpa_goodproperty.name = goodProperty.goodsAttributeName;
            bpa_goodproperty.parentid ="0";
            bpa_goodproperty.id = goodProperty.goodsAttributeId;
            bpa_goodproperty.userID="超级管理员";
            QueryDB.AddGoodsProperty(bpa_goodproperty);

            //子属性添加
            goodProperty.goodsAttributeValueList.forEach(attributeValue->{
                BPA_GOODPROPERTY bpa_goodpropertySub = new BPA_GOODPROPERTY();
                bpa_goodpropertySub.name = attributeValue.attributeValue;
                bpa_goodpropertySub.parentid = goodProperty.goodsAttributeId;
                bpa_goodpropertySub.id = attributeValue.goodsAttributeValueId;
                bpa_goodproperty.userID="超级管理员";
                QueryDB.AddGoodsProperty(bpa_goodpropertySub);
            });
        }) ;
    }

    /**
     * 同步云端商品信息到本地
     * @param item
     * @param goods
     */
    private static void GoodInfoSynchronous(DeviceGoodInfo item,List<BPA_GOODS> goods){
        if(item.goodsInfoList!=null){
            item.goodsInfoList.forEach(goodinfo->{
                BPA_GOODS bpa_goods =new BPA_GOODS();
                bpa_goods.id = goodinfo.goodsId;
                bpa_goods.name = goodinfo.goodsName;
                bpa_goods.materialids = getMaterialids(goodinfo);
                bpa_goods.goodtype=item.goodsTypeId;
                bpa_goods.status=1;
                bpa_goods.issc=1;
                bpa_goods.maketime=180;
                bpa_goods.url="";
                bpa_goods.foreignKeyRe="";
                QueryDB.AddGoods(bpa_goods);
            });
        }
    }

    /**
     * 获取商品工艺物料组合
     * @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);
    }

    /**
     * 同步云端配方详细信息到本地
     * @param item
     * @param goodReciepeNames
     */
    private static void GoodRecipeSynchronous(DeviceGoodInfo item,List<BPA_GOODSRECIPENAME> goodReciepeNames) {
        if(item.goodsInfoList!=null){
            List<BPA_GOODPROPERTY> goodProps = QueryDB.GetGoodsSubPropertyALL();
            List<BPA_MATERIAL> bpaMaterials  =  QueryDB.GetMaterialALL();
            item.goodsInfoList.forEach(goodinfo->{
                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;
                    QueryDB.AddGoodsRecipeName(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();
                            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.recipeID=bpa_goodsrecipename.id;
                                QueryDB.AddGoodsSrecipe(bpa_goodsrecipe);
                            }
                        });
                    });
                });
            });
        }
    }

    /**
     * 获取子商品名称
     * @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("_");
        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("_") ;
        }
        return recpipeNameTemp.toString().substring(0, recpipeNameTemp.length() - 1);
    }

}
