package com.bonait.bnframework.common.view;

import static com.bonait.bnframework.MainApplication.getContext;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.ConfigName;
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.image.MyBitmapUtils;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.model.mode.BomTypeInfo;
import com.bonait.bnframework.common.model.mode.FoodMenuInfo;
import com.bonait.bnframework.common.model.mode.GoodsParentTypeInfo;
import com.bonait.bnframework.common.model.mode.GoodsTypeInfo;
import com.bonait.bnframework.common.model.mode.GoodsUintInfo;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.newgood_adapter;
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;

public class AddGoodDialog extends Dialog {

    /**
     * 数据接口
     */
    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;
    public ImageView cpfm;
    public EditText edittext,edittext1;
    public Spinner editsp_fl;
    public RecyclerView recycler_view_wl;

    private onNoOnclickListener noOnclickListener;//取消按钮被点击了的监听器
    private onYesOnclickListener yesOnclickListener;//确定按钮被点击了的监听器

    /**
     * 设置取消按钮的显示内容和监听
     *
     * @param onNoOnclickListener
     */
    public void setNoOnclickListener(onNoOnclickListener onNoOnclickListener) {
        this.noOnclickListener = onNoOnclickListener;
    }

    /**
     * 设置确定按钮的显示内容和监听
     *
     * @param str
     * @param onYesOnclickListener
     */
    public void setYesOnclickListener(String str, onYesOnclickListener onYesOnclickListener) {
        if (str != null) {
            yesStr = str;
        }
        this.yesOnclickListener = onYesOnclickListener;
    }

    public AddGoodDialog(Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_add_good);
        //按空白处不能取消动画
        setCanceledOnTouchOutside(false);
        //初始化界面控件
        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);
                        ToastUtils.info("菜谱生成成功!");
                        if (yesOnclickListener != null) {
                            yesOnclickListener.onYesClick(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);
                        ToastUtils.info("菜谱修改成功!");
                        if (yesOnclickListener != null) {
                            yesOnclickListener.onYesClick(Data);
                        }
                    }

                }
            }
        });

        close_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (noOnclickListener != null) {
                    noOnclickListener.onNoClick();
                }
            }
        });

        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)
            {
                ids=item.id+",";
                if(item.isSelect)
                {
                    issc=true;
                }
            }

            //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);

        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);
            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++;
            }
        }

        //查询物料数据
        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(BPA_GOODS data, ArrayList<BPA_GOODSTYPE> types, Activity activity) {
        Data = data;
        Types=types;
        activity_ma=activity;
    }

    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);
    }

    /**
     * 设置确定按钮和取消被点击的接口
     */
    public interface onYesOnclickListener {
        public void onYesClick(BPA_GOODS data);
    }

    /**
     * 取消按钮
     */
    public interface onNoOnclickListener {
        public void onNoClick();
    }
    static Window dow;
    @Override
    public void show() {
        super.show();
        /**
         * 设置宽度全屏，要设置在show的后面
         */
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.width= ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height= ViewGroup.LayoutParams.MATCH_PARENT;
        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        getWindow().setAttributes(layoutParams);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LOW_PROFILE
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(keyboardVisibilityListener);
        dow=getWindow();
    }

    private static ViewTreeObserver.OnGlobalLayoutListener keyboardVisibilityListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // 在此处处理键盘关闭事件
            // 检查键盘的可见性和高度等信息来判断键盘是否关闭
            dow.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LOW_PROFILE
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    };

    @Override
    public void dismiss() {
        super.dismiss();
        MessageManager.getInstance().unRegisterMessageReceiver(activity_ma);
    }
}
