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

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

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
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_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.MyImage;
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.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.gongxubuzhou_adapter;
import com.bonait.bnframework.modules.home.adapter.lcsz_adapter;
import com.bonait.bnframework.modules.home.fragment.mode.fragment_gx;
import com.bonait.bnframework.modules.home.fragment.mode.item_gx;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.youth.banner.Banner;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DiyActivity extends BaseActivity {
    @BindView(R.id.topbar)
    QMUITopBar mTopBar;
    @BindView(R.id.edittext)
    EditText edittext;//菜谱名称
    @BindView(R.id.cpfm)
    ImageView cpfm;//菜谱封面
    @BindView(R.id.zzsc)
    EditText zzsc;//制作时长
    @BindView(R.id.check)
    CheckBox check;//默认收藏
    @BindView(R.id.Banner_Main)
    Banner Banner_Main;//轮播图
    //用于存放获取的图片
    List<Drawable> Banner_list = new ArrayList<>();

    @BindView(R.id.hrgx)
    Spinner hrgx;//工序
    Map<String,String> hrgx_map = new LinkedHashMap<>();
    Map<String,Integer> hrgx_map_index = new LinkedHashMap<>();

    @BindView(R.id.gxchid)
    LinearLayout gxchid;//工序子集

    @BindView(R.id.datatab_gxbz)
    ListView datatab_gxbz;//工序步骤
    public gongxubuzhou_adapter gxbz_adapter=null;
    public String imageUrl="";
    /**
     * 工序步骤
     */
    public ArrayList<BPA_GOODSRECIPE> bpa_goodsrecipes=new ArrayList<>();
    /**
     * 是否人工单击
     */
    public boolean isUserClicked =false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diy);//属性绑定
        ButterKnife.bind(this);
        initTopBar();
        initData();
    }
    private void initData()
    {
        //1.初始化轮播图
        Drawable_Get(Banner_list);
        //2.初始化工序
        ArrayList<BPA_PROCESS> data=QueryDB.GetProcessALL();
        int i=0;String id="";
        for (BPA_PROCESS item:data)
        {
            hrgx_map.put(item.name,item.id);
            hrgx_map_index.put(item.name,i);
            if(i==0)
            {
                id= item.id;
            }
            i++;
        }
        ArrayAdapter<String> adapter_kk = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, new ArrayList<>(hrgx_map.keySet()));
        adapter_kk.setDropDownViewResource(R.layout.spinner_dropdown_item);
        hrgx.setAdapter(adapter_kk);

        hrgx.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                isUserClicked = true;
                view.performClick();
                return false;
            }
        });
        hrgx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if(isUserClicked)//不是用户点击返回
                {
                    String id= hrgx_map.get(hrgx.getSelectedItem().toString());
                    SelectItemFrom(id);
                    isUserClicked=false;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
        SelectItemFrom(id);
        //3.工序步骤
        gxbz_adapter = new gongxubuzhou_adapter(getContext(), R.layout.gx_item, (List<BPA_GOODSRECIPE>) bpa_goodsrecipes,null);
        datatab_gxbz.setAdapter(gxbz_adapter);

        datatab_gxbz.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
                // TODO Auto-generated method stub
                gxbz_adapter.setSelectedPosition(position);
                gxbz_adapter.notifyDataSetInvalidated();

                SetSelectGX(bpa_goodsrecipes.get(position));//单击工序行，显示变量
            }
        });

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

    /**
     * 根据选中步骤显示变量
     * @param goodsrecipe
     */
    public void SetSelectGX(BPA_GOODSRECIPE goodsrecipe)
    {
        try
        {
            //1.根据工序名称显示工序集合
            hrgx.setSelection(hrgx_map_index.get(goodsrecipe.processname));
            String id= hrgx_map.get(hrgx.getSelectedItem().toString());
            SelectItemFrom(id);

            //2.根据工序变量集合-获取变量名称和值
            final HashMap<String,String> formulation=new HashMap<>();
            //region 获取变量名称和值
            String text=goodsrecipe.processvalue;
            List<String> data=new ArrayList<>();
            if(text.contains("|"))
            {
                String[] res= text.split("[|]");
                for (int i=0;i<res.length;i++)
                {
                    data.add(res[i]);
                }
            }else
            {
                data.add(text);
            }
            for(String item:data)
            {
                if(!item.isEmpty() && item.contains(","))
                {
                    String[] wl= item.split("[,]");
                    if (wl != null && wl.length == 2)
                    {
                        String name=wl[0];
                        String val=wl[1];
                        formulation.put(name,val);
                    }
                }
            }
            //endregion

            //3.查询子集-填充变量
            for (Map.Entry<String, String> entry : formulation.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                String STR= formulation.get(key);
            }

            for (int i = 0; i < gxchid.getChildCount(); i++) {
                fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
                String res= formulation.get(gongxu.model.name);
                if(res!=null)
                {
                    gongxu.SetValues(res);
                }
            }
        }catch (Exception ex)
        {
        }
    }

    /**
     * 根据选中工序id显示集合
     * @param id
     */
    public  void SelectItemFrom(String id)
    {
        try
        {
            gxchid.removeAllViews();
            ArrayList<BPA_PROCESSModel> mode= QueryDB.GetProcessModelProcessID(id);
            if(mode.size()>0)//工序
            {
                for (BPA_PROCESSModel item : mode)
                {
                    item_gx gx=new item_gx();
                    gx.datatype=item.datatype;
                    gx.name=item.name;
                    gx.data=item.data;
                    gx.IsWL=false;
                    fragment_gx gongxu=new fragment_gx(this,null,gx);
                    gxchid.addView(gongxu);
                }
            }else //物料
            {
                ArrayList<BPA_MATERIAL> materials= QueryDB.GetMaterialALL();
                for (BPA_MATERIAL item2 : materials)
                {
                    item_gx gx=new item_gx();
                    gx.datatype=0;//液体料都是数字
                    gx.name=item2.name;
                    gx.IsWL=true;
                    fragment_gx gongxu=new fragment_gx(this,null,gx);
                    gxchid.addView(gongxu);
                }
            }
        }catch (Exception ex)
        {
        }
    }

    /**
     * 获取选中行的变量
     * @return
     */
    public BPA_GOODSRECIPE GetSelectItemFromValue()
    {
        BPA_GOODSRECIPE pf=new BPA_GOODSRECIPE();
        try
        {
            String name= hrgx.getSelectedItem().toString();
            boolean IsVerify=true;
            String description="";
            //  延迟,100|延迟,100|延迟,100|延迟,100|
            String data="";
            String desc="";
            if(name.equals("液体料"))
            {
                pf.materialType=0;
                for (int i = 0; i < gxchid.getChildCount(); i++) {
                    fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
                    String values= gongxu.GetValues();
                    if(!values.isEmpty())
                    {
                        data+=gongxu.model.name+","+values+"|";
                        desc+=values+",";
                    }
                }

                if(data.isEmpty())
                {
                    IsVerify=false;
                    description+="物料-不能为空,请勾选一个物料\n";
                }
            }else
            {
                pf.materialType=1;
                for (int i = 0; i < gxchid.getChildCount(); i++) {
                    fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
                    String values= gongxu.GetValues();
                    if(values.isEmpty())
                    {
                        IsVerify=false;
                        description+=gongxu.model.name +"-不能为空\n";
                    }else
                    {
                        data+=gongxu.model.name+","+values+"|";
                        desc+=values+",";
                    }
                }
            }
            if(IsVerify)
            {
                pf.processname=name;
                pf.processms= name+"("+desc.substring(0,desc.length()-1) +")";
                pf.processvalue=data.substring(0,data.length()-1);
                return pf;
            }else
            {
                ToastUtils.info("数据验证失败,原因:"+description);
                return null;
            }
        }catch (Exception ex)
        {
            return null;
        }
    }
    private void initTopBar() {
        mTopBar.setTitle("DIY模式");
        mTopBar.addLeftImageButton(R.mipmap.fanhui,R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
    /**
     * 获取图片存放到list中
     * @param arrayList
     */
    private void Drawable_Get(List arrayList) {
        //把他们存放到一个list集合中
        arrayList.add(getResources().getDrawable(R.mipmap.image1));
        arrayList.add(getResources().getDrawable(R.mipmap.image2));
        arrayList.add(getResources().getDrawable(R.mipmap.image3));
        arrayList.add(getResources().getDrawable(R.mipmap.image4));
        //调用轮播图设置方法
        Banner_Set(Banner_list);
    }
    /**
     * 将图片存放到轮播图中
     * @param arrayList
     */
    private void Banner_Set(List arrayList) {
        //这是设置轮播图的关键位置，setImages(list) 设置轮播图的图片资源
        //setImageLoader（一个实体类）用于加载图片到手机页面上显示
        Banner_Main.setImages(Banner_list).setImageLoader(new MyImage()).start();
    }
    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.add_hrgx,R.id.update_gx,R.id.delete_gx,R.id.shangyi,R.id.xiayi,R.id.caozuomoshi,R.id.shengchengcaipu,R.id.cpfm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cpfm://菜谱封面
                // 跳转到登录页面
                Intent intent = new Intent(getContext(), ImageChooseActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            case R.id.add_hrgx://添加工序
                BPA_GOODSRECIPE goodsrecipe= GetSelectItemFromValue();
                if(goodsrecipe!=null)
                {
                    bpa_goodsrecipes.add(GetSelectItemFromValue());
                    gxbz_adapter.notifyDataSetChanged();
                }
                break;
            case R.id.update_gx://修改工序
                int index_update= gxbz_adapter.getSelectedPosition();
                if(index_update>=0 && index_update<bpa_goodsrecipes.size())
                {
                    BPA_GOODSRECIPE obj_update= (BPA_GOODSRECIPE)bpa_goodsrecipes.get(index_update);
                    String selectname= hrgx.getSelectedItem().toString();
                    if(!obj_update.processname.equals(selectname))
                    {
                        ToastUtils.info("请先选择工序！");
                        return;
                    }
                    bpa_goodsrecipes.set(index_update,GetSelectItemFromValue());
                    gxbz_adapter.notifyDataSetChanged();
                    ToastUtils.info("修改步骤"+(index_update+1)+":"+obj_update.processname+"成功！");
                }else
                {
                    ToastUtils.info("请先选择工序！");
                }
                break;
            case R.id.delete_gx://删除工序
                int index_delete= gxbz_adapter.getSelectedPosition();
                if(index_delete>=0 && index_delete<bpa_goodsrecipes.size())
                {
                    BPA_GOODSRECIPE obj_delete= (BPA_GOODSRECIPE)bpa_goodsrecipes.get(index_delete);
                    bpa_goodsrecipes.remove(obj_delete);
                    gxbz_adapter.notifyDataSetChanged();

                    //移动光标
                    if(index_delete-1>=0)
                    {
                        SetSelectPos(index_delete-1);
                    }
                    ToastUtils.info("删除工序"+obj_delete.processname+"成功！");
                }else
                {
                    ToastUtils.info("请先选择工序！");
                }
                break;
            case R.id.shangyi://上移
                int index_up= gxbz_adapter.getSelectedPosition();;
                if(index_up>0)
                {
                    BPA_GOODSRECIPE obj_up= (BPA_GOODSRECIPE)bpa_goodsrecipes.get(index_up);
                    bpa_goodsrecipes.remove(obj_up);
                    bpa_goodsrecipes.add(index_up-1,obj_up);
                    gxbz_adapter.notifyDataSetChanged();

                    //移动光标
                    SetSelectPos(index_up-1);
                }else
                {
                    ToastUtils.info("已经最顶部！");
                }
                break;
            case R.id.xiayi://下移
                int index_down= gxbz_adapter.getSelectedPosition();
                if(index_down<bpa_goodsrecipes.size()-1 && index_down>=0)
                {
                    BPA_GOODSRECIPE obj_down= (BPA_GOODSRECIPE)bpa_goodsrecipes.get(index_down);
                    bpa_goodsrecipes.remove(obj_down);
                    bpa_goodsrecipes.add(index_down+1,obj_down);
                    gxbz_adapter.notifyDataSetChanged();

                    //移动光标
                    SetSelectPos(index_down+1);
                }else
                {
                    ToastUtils.info("已经最底部！");
                }
                break;
            case R.id.caozuomoshi://操作模式
                ToastUtils.info("操作模式");
                break;
            case R.id.shengchengcaipu://生成菜谱
                String name=edittext.getText().toString();


                if(name.isEmpty())
                {
                    ToastUtils.info("菜谱名称不能为空!");
                    return;
                }else
                {
                    boolean isSucess= QueryDB.GetGoodsIs(name);
                    if(isSucess)
                    {
                        ToastUtils.info("菜谱名称已存在!");
                        return;
                    }
                    //按钮点击
                    String title = "生成菜谱操作提示！";
                    String message = "请问客官确定要生成["+name+"]菜谱吗?";
                    AlertDialogUtils.showDialog(view.getContext(), title, message, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            int sc=60*3;
                            if(!zzsc.getText().toString().isEmpty() && !zzsc.getText().toString().equals("0"))
                            {
                                sc=Integer.parseInt(zzsc.getText().toString());
                            }

                            ArrayList<BPA_GOODS> goods=QueryDB.GetGoodsALL();
                            BPA_GOODS good=new BPA_GOODS();
                            good.name=name;
                            good.status=1;
                            good.sort=goods.size()+1;
                            good.maketime=sc;
                            good.issc=check.isChecked()?1:0;
                            good.url=imageUrl;
                            QueryDB.AddGoods(good);
                            for (int k=0;k<bpa_goodsrecipes.size();k++)
                            {
                                BPA_GOODSRECIPE item=bpa_goodsrecipes.get(k);
                                item.goodsID=good.id;
                                item.sort=k+1;
                                QueryDB.AddGoodsSrecipe(item);
                            }
                            ToastUtils.info("菜谱生成成功!");
                            dialog.dismiss();
                        }
                    });

                }
                break;
        }
    }
    public void SetSelectPos(int index)
    {
        //移动光标
        gxbz_adapter.setSelectedPosition(index);
        gxbz_adapter.notifyDataSetInvalidated();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    protected boolean canDragBack() {
        return false;
    }

}