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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;

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

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.res.ResMaterilas;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.image.MyBitmapUtils;
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.newmeatrilselect_adapter;
import com.bonait.bnframework.modules.home.fragment.from.ImageChooseActivity;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;

public class add_good_control extends LinearLayout {

    /**
     * 数据接口
     */
    public BPA_GOODS Data=null;
    /**
     * 商品类型
     */
    public ArrayList<BPA_GOODSTYPE> Types=new ArrayList<>();
    /**
     * 当前物料数据
     */
    public ArrayList<ResMaterilas> resMaterilas=new ArrayList<>();


    //确定文本和取消文本的显示内容
    private String yesStr;

    /**
     * 取消按钮
     */
    public Button close_from,xinjian,save_xinjian;
    public ImageView cpfm;

    public EditText edittext,edittext1;
    public Spinner editsp_fl;
    public RecyclerView recycler_view_wl;

    /**
     * 点击事件
     */
    public MyClickListener mListener=null;
    private View root;
    public add_good_control(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        root= LayoutInflater.from(context).inflate(R.layout.dialog_add_good, this);
        ButterKnife.bind(this, root);
    }

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

    /**
     * 初始化界面的确定和取消监听器
     */
    private void initEvent() {
        //设置确定按钮被点击后，向外界提供监听
        xinjian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(DataVerification()) {

                    ArrayList<BPA_GOODS> goods = QueryDB.GetGoodsALL();
                    if(Data== null)//新增
                    {
                        boolean isSucess = QueryDB.GetGoodsIs(edittext.getText().toString());
                        if(isSucess)
                        {
                            ToastUtils.info("菜谱名称已存在!");
                            return;
                        }
                        Data=new BPA_GOODS();
                        Data.name = edittext.getText().toString();
                        Data.status = 1;
                        Data.sort = goods.size() + 1;
                        Data.maketime = 180;
                        Data.issc = 1;
                        Data.url = url;
                        Data.foreignKeyRe=edittext1.getText().toString();
                        Data.goodtype=map_fl.get(editsp_fl.getSelectedItem().toString());
                        Data.materialids=ids;
                        QueryDB.AddGoods(Data);
                        if (mListener != null) {
                            mListener.clickListenerNew(v,1,Data);
                        }
                    }else //修改
                    {
                        Data.name = edittext.getText().toString();
                        Data.status = 1;
                        Data.sort = goods.size() + 1;
                        Data.maketime = 180;
                        Data.issc = 1;
                        Data.url = url;
                        Data.foreignKeyRe=edittext1.getText().toString();
                        Data.goodtype=map_fl.get(editsp_fl.getSelectedItem().toString());
                        Data.materialids=ids;
                        QueryDB.UpdateGoods(Data);
                        if (mListener != null) {
                            mListener.clickListenerNew(v,1,Data);
                        }
                    }

                }
            }
        });

        save_xinjian.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(DataVerification()) {

                    ArrayList<BPA_GOODS> goods = QueryDB.GetGoodsALL();
                    if(Data== null)//新增
                    {
                        boolean isSucess = QueryDB.GetGoodsIs(edittext.getText().toString());
                        if(isSucess)
                        {
                            ToastUtils.info("菜谱名称已存在!");
                            return;
                        }
                        Data=new BPA_GOODS();
                        Data.name = edittext.getText().toString();
                        Data.status = 1;
                        Data.sort = goods.size() + 1;
                        Data.maketime = 180;
                        Data.issc = 1;
                        Data.url = url;
                        Data.foreignKeyRe=edittext1.getText().toString();
                        Data.goodtype=map_fl.get(editsp_fl.getSelectedItem().toString());
                        Data.materialids=ids;
                        QueryDB.AddGoods(Data);
                        if (mListener != null) {
                            mListener.clickListenerNew(v,2,Data);
                        }
                    }else //修改
                    {
                        Data.name = edittext.getText().toString();
                        Data.status = 1;
                        Data.sort = goods.size() + 1;
                        Data.maketime = 180;
                        Data.issc = 1;
                        Data.url = url;
                        Data.foreignKeyRe=edittext1.getText().toString();
                        Data.goodtype=map_fl.get(editsp_fl.getSelectedItem().toString());
                        Data.materialids=ids;
                        QueryDB.UpdateGoods(Data);
                        if (mListener != null) {
                            mListener.clickListenerNew(v,2,Data);
                        }
                    }

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

        cpfm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), ImageChooseActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                activity_ma.startActivity(intent);
            }
        });

        //图标选择
        MessageManager.getInstance().registerMessageReceiver(activity_ma, MessageName.ClickImage, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    url=(String) msg;
                    new MyBitmapUtils().disPlay(cpfm,url);
                }
            }
        });
    }

    public String ids="";
    /**
     * 数据验证
     * @return
     */
    public boolean DataVerification()
    {
        boolean IsSucees=false;
        try
        {
            if(edittext.getText().toString().isEmpty())
            {
                ToastUtils.info("名称不能为空!");
                return false;
            }

            boolean issc=false;
            ids="";
            for (ResMaterilas item:resMaterilas)
            {
                if(item.isSelect)
                {
                    ids+=item.id+",";
                    issc=true;
                }
            }

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

            //resMaterilas
            if(issc==false)
            {
                ToastUtils.info("必须选择一个物料!");
                return false;
            }
            return true;
        }catch (Exception ex)
        {
            ToastUtils.error("数据验证异常!"+ex.getMessage());
            return IsSucees;
        }
    }

    Activity activity_ma;
    public String url="";
    Map<String,String> map_fl = new LinkedHashMap<>();
    /**
     * 初始化界面控件
     */
    private void initView() {
        close_from = (Button) findViewById(R.id.close_from);
        xinjian = (Button) findViewById(R.id.xinjian);
        save_xinjian= (Button) findViewById(R.id.save_xinjian);
        cpfm = findViewById(R.id.cpfm);

        edittext = findViewById(R.id.edittext);
        edittext1 = findViewById(R.id.edittext1);
        editsp_fl = findViewById(R.id.editsp_fl);

        recycler_view_wl = findViewById(R.id.recycler_view_wl);
    }

    /**
     * 初始化界面控件的显示数据
     */
    private void initData() {
        for (BPA_GOODSTYPE item:Types)
        {
            map_fl.put(item.name,item.id);
        }
        SetAdapter(editsp_fl,map_fl);
        //如果设置按钮的文字
        if (yesStr != null) {
            xinjian.setText(yesStr);
        }

        //数据不为空 那么就是修改
        if(Data!=null)
        {
            edittext.setText(Data.name);
            edittext1.setText(Data.foreignKeyRe);
            new MyBitmapUtils().disPlay(cpfm,Data.url);
            url=Data.url;
            int index=0;
            for (Map.Entry<String, String> entry : map_fl.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if(value.equals(Data.goodtype))
                {
                    editsp_fl.setSelection(index);
                }
                index++;
            }
        }else
        {
            edittext.setText("");
            edittext1.setText("");
            new MyBitmapUtils().disPlay(cpfm,"");
            url="";
        }

        //查询物料数据
        ArrayList<BPA_MATERIAL> materials= QueryDB.GetMaterialALL();
        if(materials!=null && materials.size()>0)
        {
            resMaterilas.clear();
            for (BPA_MATERIAL item:materials)
            {
                ResMaterilas mk=new ResMaterilas();
                mk.name=item.name;
                mk.id=item.id;
                mk.isSelect=false;
                if(Data!=null && !Data.materialids.isEmpty())
                {
                    if(Data.materialids.contains(item.id))
                    {
                        mk.isSelect=true;
                    }
                }
                resMaterilas.add(mk);
            }
        }
        MyLayoutManager layout = new MyLayoutManager();
        layout.setAutoMeasureEnabled(true);
        recycler_view_wl.setLayoutManager(layout);
        newmeatrilselect_adapter adapter = new newmeatrilselect_adapter(getContext(), resMaterilas);
        recycler_view_wl.setAdapter(adapter);
    }
    /**
     * 从外界Activity为Dialog 设置数据
     *
     * @param data
     */
    public void setData(String str, BPA_GOODS data, ArrayList<BPA_GOODSTYPE> types, Activity activity) {
        if (str != null) {
            yesStr = str;
        }

        Data = data;
        Types=types;
        activity_ma=activity;

        Init();
    }

    public void SetAdapter(Spinner spinner,Map<String,String> map)
    {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, new ArrayList<>(map.keySet()));
        adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }
}
