package com.bonait.bnframework.modules.home.fragment.mode;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bonait.bnframework.R;
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_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_MATERIAL;
import com.bonait.bnframework.common.db.res.ResGoodProperty;
import com.bonait.bnframework.common.db.res.ResGoodsRecipe;
import com.bonait.bnframework.common.db.res.ResMaterilas;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.modules.home.adapter.newneatril_adapter;
import com.bonait.bnframework.modules.home.adapter.pfsx_adapter;
import com.bonait.bnframework.modules.home.adapter.xxpf_adapter;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class add_pf_control extends LinearLayout {// implements MyClickListener


    @BindView(R.id.peifang_queren)
    Button peifang_queren;

    @BindView(R.id.save_peifang_queren)
    Button save_peifang_queren;
    @BindView(R.id.close_from)
    Button close_from;

    @BindView(R.id.recycler_view_wl_click)
    RecyclerView recycler_view_wl_click;

    public BPA_GOODSRECIPENAME bpaGoodsrecipename=null;
    public BPA_GOODS Good=null;
    @BindView(R.id.edittext)
    EditText edittext;//配方名称

    @BindView(R.id.datatab_sx)
    RecyclerView datatab_sx;

    @BindView(R.id.datatab_pf)
    ListView datatab_pf;

    @BindView(R.id.title)
    TextView title;//配方名称


    /**
     * 当前物料数据
     */
    public ArrayList<BPA_MATERIAL> resMaterilas=new ArrayList<>();


    /**
     * 属性数据
     */
    ArrayList<ResGoodProperty> bpa_goodproperties = new ArrayList<>();
    /**
     * 点击事件
     */
    public MyClickListener mListener=null;
    private View root;
    public Context acontext=null;
    public add_pf_control(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        root= LayoutInflater.from(context).inflate(R.layout.dialog_add_pf, this);
        ButterKnife.bind(this, root);
        acontext=context;
        Init();
    }


    public void Init()
    {
        //初始化界面控件的事件
        initEvent();
    }


    private void initData()
    {
        //1.查询物料数据 填充物料点击事件
        resMaterilas.clear();
        resMaterilas= QueryDB.GetMaterialALL();
        MyLayoutManager layout = new MyLayoutManager();
        layout.setAutoMeasureEnabled(true);
        recycler_view_wl_click.setLayoutManager(layout);
        newneatril_adapter adapter = new newneatril_adapter(getContext(), resMaterilas, new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
                BPA_MATERIAL m=(BPA_MATERIAL)data;

                ResGoodsRecipe cipe=new ResGoodsRecipe();
                cipe.sort=0;
                cipe.materialID=m.id;
                cipe.materialName=m.name;
                cipe.value="0";
                if (DataBus.getInstance().Recipe==null)
                {
                    DataBus.getInstance().Recipe=new ArrayList<>();
                }
                DataBus.getInstance().Recipe.add(cipe);

                adapter4.notifyDataSetChanged();
            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {

            }
        });
        recycler_view_wl_click.setAdapter(adapter);

        //2.填充规则数据，查询所有属性大类


        if(bpaGoodsrecipename==null)
        {
            for(ResGoodProperty item:bpa_goodproperties){
                int i=0;
                for(ResGoodProperty c:item.child){
                    c.isSelect=(i==0);
                    i++;
                }
            }
            edittext.setText(GetSelectName());
        }else
        {
            for(ResGoodProperty item:bpa_goodproperties){
                for(ResGoodProperty c:item.child) {
                    c.isSelect= bpaGoodsrecipename.design!=null && bpaGoodsrecipename.design.contains(c.id);
                }
            }
        }

        LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        datatab_sx.setLayoutManager(layoutManager);

        pfsx_adapter sxadapter = new pfsx_adapter(getContext(), bpa_goodproperties);
        datatab_sx.setAdapter(sxadapter);

        InitTab();
    }
    xxpf_adapter adapter4;
    public void InitTab()
    {
        DataBus.getInstance().Recipe.clear();
        if(bpaGoodsrecipename!=null)
        {
            DataBus.getInstance().Recipe = QueryDB.GetGoodsSreciperecipeList(bpaGoodsrecipename.id);

        }else
        {
            for(BPA_MATERIAL wl:resMaterilas)
            {
                if(Good.materialids!=null && !Good.materialids.isEmpty() && Good.materialids.contains(wl.id))
                {
                    ResGoodsRecipe cipe=new ResGoodsRecipe();
                    cipe.sort=0;
                    cipe.materialID=wl.id;
                    cipe.materialName=wl.name;
                    cipe.value="0";
                    cipe.goodsID=Good.id;
                    DataBus.getInstance().Recipe.add(cipe);
                }
            }
        }

        if( DataBus.getInstance().Recipe==null)
        {
            DataBus.getInstance().Recipe=new ArrayList<>();
        }
        adapter4= new xxpf_adapter(getContext(), R.layout.xxpf_item, DataBus.getInstance().Recipe,listener);
        datatab_pf.setAdapter(adapter4);
    }


    /**
     * 设置数据
     * @param name
     */
    public void SetData(BPA_GOODSRECIPENAME name, BPA_GOODS good,ArrayList<ResGoodProperty> properties)
    {
        try {
            //根据商品类型判断属性
            bpa_goodproperties.clear();
            for (ResGoodProperty pro:properties)
            {
                if(pro.GoodsTypeId!=null && !pro.GoodsTypeId.isEmpty())
                {
                    if(pro.GoodsTypeId.contains(good.goodtype))
                    {
                        bpa_goodproperties.add(pro);
                    }
                }else
                {
                    bpa_goodproperties.add(pro);
                }
            }

            bpaGoodsrecipename=name;
            Good=good;
            if(name!=null)
            {
                edittext.setText(bpaGoodsrecipename.name+"");
            }else
            {
                edittext.setText("");
            }

            if(bpaGoodsrecipename==null)//新增
            {
                save_peifang_queren.setVisibility(View.VISIBLE);

            }else
            {
                save_peifang_queren.setVisibility(View.GONE);
            }

            title.setText(Good.name+"");
            initData();
        }catch (Exception ex)
        {

        }
    }

    private Activity findActivity(@NonNull Context context) {
        if (context instanceof Activity) {
            return (Activity) context;
        } else if (context instanceof ContextWrapper) {
            return findActivity(((ContextWrapper) context).getBaseContext());
        } else {
            return null;
        }
    }

    private void initEvent()
    {
        peifang_queren.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null && SaveData()) {
                    mListener.clickListenerNew(view,1,null);
                }
            }
        });

        save_peifang_queren.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null && SaveData()) {
                    mListener.clickListenerNew(view,2,null);
                }
            }
        });
        close_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.clickListenerNew(v,0,null);
                }
            }
        });

        Activity activity = findActivity(acontext);
        if (activity != null) {
            MessageManager.getInstance().registerMessageReceiver(activity, MessageName.ClickProperty, new MessageLooper.OnMessageListener() {
                @Override
                public void onMessage(Object msg) {
                    if (msg != null) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    edittext.setText(GetSelectName());
                                } catch (Exception e) {

                                }
                            }
                        });
                    }
                }
            });
        }
    }

    public void destroy(){
        Activity activity = findActivity(acontext);
        if (activity != null) {
            MessageManager.getInstance().unRegisterMessageReceiver(activity);
        }
        listener = null;
        resMaterilas.clear();
        bpa_goodproperties.clear();
        resMaterilas = null;
        bpa_goodproperties = null;
        if(adapter4!=null){
            adapter4.clear();
            adapter4 = null;
        }

        mListener = null;
        if(datatab_sx!=null){
            datatab_sx.setAdapter(null);
            datatab_pf.setAdapter(null);
        }

        acontext = null;
        pfname = null;
        ggids = null;
    }

    /**
     * 保存数据
     */
    public boolean SaveData()
    {
        if(DataValidation())
        {
            if(bpaGoodsrecipename==null)//新增
            {
                //新增配方名称
                BPA_GOODSRECIPENAME n=new BPA_GOODSRECIPENAME();
                n.name=pfname;
                n.design=ggids;
                n.goodsID=Good.id;
                QueryDB.AddGoodsRecipeName(n);
                //新增配方信息
                for (ResGoodsRecipe i:DataBus.getInstance().Recipe)
                {
                    BPA_GOODSRECIPE good=new BPA_GOODSRECIPE();
                    good.materialID=i.materialID;
                    good.recipeID=n.id;
                    good.goodsID=Good.id;
                    good.value=i.value;
                    good.sort=i.sort;


                    QueryDB.AddGoodsSrecipe(good);
                }
            }else //修改
            {
                bpaGoodsrecipename.name=pfname;
                bpaGoodsrecipename.design=ggids;
                bpaGoodsrecipename.goodsID=Good.id;
                QueryDB.UpdateGoodsRecipeName(bpaGoodsrecipename);

                ArrayList<ResGoodsRecipe> re= QueryDB.GetGoodsSreciperecipeList(bpaGoodsrecipename.id);
                for(ResGoodsRecipe item:re)
                {
                    QueryDB.DeleteGoodsSrecipe(item.id);
                }

                for (ResGoodsRecipe i:DataBus.getInstance().Recipe)
                {
                    BPA_GOODSRECIPE good=new BPA_GOODSRECIPE();
                    good.materialID=i.materialID;
                    good.recipeID=bpaGoodsrecipename.id;
                    good.goodsID=Good.id;
                    good.value=i.value;
                    good.sort=i.sort;

                    QueryDB.AddGoodsSrecipe(good);
                }
            }
            return true;
        }
        return false;
    }
    /**
     * 获取选中名称
     * @return
     */
    public String GetSelectName()
    {
        String names=Good.name+"_";
        for(ResGoodProperty item:bpa_goodproperties)
        {
            for(ResGoodProperty k:item.child)
            {
                if(k.isSelect)
                {
                    names+=k.name+"_";
                }
            }
        }
        return names.substring(0, names.length() - 1);
    }

    String pfname="";//配方名称集合
    String ggids="";//规格id集合
    /**
     * 数据验证
     */
    public boolean DataValidation()
    {
        boolean isSuceess=false;
        //1.数据名称不能为空
        pfname=edittext.getText().toString();
        if(pfname.isEmpty())
        {
            ToastUtils.warning("配方名称不能为空!");
            return isSuceess;
        }

        ggids="";
        for(ResGoodProperty item:bpa_goodproperties)
        {
            for(ResGoodProperty k:item.child)
            {
                if(k.isSelect)
                {
                    ggids+=k.id+",";
                }
            }
        }

        if(!ggids.isEmpty())
        {
            ggids=ggids.substring(0, ggids.length() - 1);
        }

        //2.必须选择一个规格
        if(DataBus.getInstance().Recipe.size()<=0)
        {
            ToastUtils.warning("配方数据表格不能为空!");
            return isSuceess;
        }

        //判断配方是否有相同规格的了
        if(bpaGoodsrecipename==null)//新增
        {
            BPA_GOODSRECIPENAME goodsrecipename = QueryDB.GetGoodsRecipeNameDesignId(ggids,Good.id);
            if (goodsrecipename != null) {
                ToastUtils.warning("已有该做法配方,不能再新增了!");
                return isSuceess;
            }
        }
        return true;
    }

    private MyClickListener listener = new MyClickListener() {
        @Override
        public void clickListener(View v, Object data) {
            switch (v.getId()) {
                case R.id.name://点击 修改

                    break;
                case R.id.button_item://删除按钮

                    break;
            }
        }

        @Override
        public void clickListenerNew(View v, int k, Object data) {

        }
    };


//    /**
//     * 点击事件
//     *
//     * @param v
//     * @param data
//     */
//    @Override
//    public void clickListener(View v, Object data) {
//
//    }
//
//    @Override
//    public void clickListenerNew(View v, int k, Object data) {
//
//    }
}
