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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

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

import com.apkfuns.logutils.LogUtils;
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_GOODSTYPE;
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.glide.GlideUtil;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.WrapContentLinearLayoutManager;
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.DisplayManager;
import com.bonait.bnframework.common.utils.KeyboardUtil;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.databinding.GoodsEditLayoutBinding;
import com.bonait.bnframework.event.ImageUrlSelectEvent;
import com.bonait.bnframework.modules.home.adapter.GoodGroupNameAdapter;
import com.bonait.bnframework.modules.home.adapter.newmeatrilselect_adapter;
import com.bonait.bnframework.modules.home.adapter.pfsx_adapter;
import com.bonait.bnframework.modules.home.fragment.from.GoodPeiFangActivity;
import com.bonait.bnframework.modules.home.fragment.from.ImageChooseActivity;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author: liup
 * @description: 添加配方  修改商品
 * @date: 2024/6/6 15:38.
 */
public class GoodsEditView extends LinearLayout {

    private GoodsEditLayoutBinding viewBinding;
    private GoodPeiFangActivity activity;
    private String url;//图片地址
    /**
     * 点击事件
     */
    public MyClickListener mListener=null;
    /**
     * 商品
     */
    public BPA_GOODS goodsData=null;
    
    public GoodsEditView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View root = LayoutInflater.from(context).inflate(R.layout.goods_edit_layout, this);
        viewBinding = GoodsEditLayoutBinding.bind(root);
        DisplayManager.scaleViewGroup(viewBinding.getRoot());
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView(){
        initListener();
    }

    /**
     * 设置数据
     *
     * @param data
     */
    public void setData(BPA_GOODS data, GoodPeiFangActivity activity) {
        if(data==null){
            ToastUtils.info("数据为空");
            return;
        }
        setVisibility(VISIBLE);
        goodsData = data;
        this.activity=activity;
        initData();
    }

    /**
     * 初始化界面控件的显示数据
     */
    private void initData() {
        //数据不为空 那么就是修改
        viewBinding.edittextName.setText(goodsData.name);
        viewBinding.edittextFk.setText(goodsData.foreignKeyRe);
        new MyBitmapUtils().disPlay(viewBinding.imgGoods,goodsData.url);
        url=goodsData.url;
        //初始化属性信息
        initPropertyData();
        initGroupDetail();
    }

    public void setListener(MyClickListener mListener){
        this.mListener = mListener;
    }

    /**
     * 按键监听
     */
    private void initListener(){
        viewBinding.getRoot().setOnClickListener(v->{
            KeyboardUtil.hideKeyboard(viewBinding.getRoot());
        });
        viewBinding.titleGoods.setOnClickListener(v->{
            if(viewBinding.contentGoods.getVisibility() == VISIBLE){
                viewBinding.contentGoods.setVisibility(GONE);
                viewBinding.icArrowGoods.setBackgroundResource(R.mipmap.ic_arrow_left);
                viewBinding.tvGoods.setText("展开");
            }else {
                viewBinding.contentGoods.setVisibility(VISIBLE);
                viewBinding.icArrowGoods.setBackgroundResource(R.mipmap.ic_arrow_down);
                viewBinding.tvGoods.setText("收起");
            }
        });
        viewBinding.titleAttribute.setOnClickListener(v->{
            if(viewBinding.contentAttribut.getVisibility() == VISIBLE){
                viewBinding.contentAttribut.setVisibility(GONE);
                viewBinding.icArrowAttribute.setBackgroundResource(R.mipmap.ic_arrow_left);
                viewBinding.tvArrowAttribute.setText("展开");
            }else {
                viewBinding.contentAttribut.setVisibility(VISIBLE);
                viewBinding.icArrowAttribute.setBackgroundResource(R.mipmap.ic_arrow_down);
                viewBinding.tvArrowAttribute.setText("收起");
            }
        });
        viewBinding.titleDetail.setOnClickListener(v->{
            if(viewBinding.recyclerDetail.getVisibility() == VISIBLE){
                viewBinding.tabTitle.setVisibility(GONE);
                viewBinding.recyclerDetail.setVisibility(GONE);
                viewBinding.icArrowDetail.setBackgroundResource(R.mipmap.ic_arrow_left);
                viewBinding.tvArrowDetail.setText("展开");
            }else {
                viewBinding.tabTitle.setVisibility(VISIBLE);
                viewBinding.recyclerDetail.setVisibility(VISIBLE);
                viewBinding.icArrowDetail.setBackgroundResource(R.mipmap.ic_arrow_down);
                viewBinding.tvArrowDetail.setText("收起");
            }
        });

        viewBinding.llImg.setOnClickListener(v->{
            Intent intent = new Intent(getContext(), ImageChooseActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
        });
        //图标选择
//        MessageManager.getInstance().registerMessageReceiver(activity, MessageName.ClickImage, new MessageLooper.OnMessageListener() {
//            @Override
//            public void onMessage(Object msg) {
//                if (msg != null) {
//                    url=(String) msg;
//                    new MyBitmapUtils().disPlay(viewBinding.imgGoods,url);
//                    GlideUtil.showImage(viewBinding.imgGoods.getContext(),url,viewBinding.imgGoods,R.mipmap.loading3);
//                    goodsData.url = url;
//                    QueryDB.UpdateGoods(goodsData);
//                    if(changeCallBack!=null){
//                        changeCallBack.onChangeGood();
//                    }
//                }
//            }
//        });

        //商品
        viewBinding.updateGoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(viewBinding.edittextName.getText().toString().isEmpty())
                {
                    ToastUtils.info("名称不能为空!");
                    return;
                }
                if(!viewBinding.edittextName.getText().toString().equals(goodsData.name)){
                    boolean isSucess = QueryDB.GetGoodsIs(viewBinding.edittextName.getText().toString());
                    if(isSucess )
                    {
                        ToastUtils.info("菜谱名称已存在!");
                        return;
                    }
                }

                goodsData.name = viewBinding.edittextName.getText().toString();
                goodsData.url = url;
                goodsData.foreignKeyRe=viewBinding.edittextFk.getText().toString();
                QueryDB.UpdateGoods(goodsData);
                if (mListener != null) {
                    mListener.clickListenerNew(v,1,goodsData);
                }
                if(changeCallBack!=null){
                    changeCallBack.onChangeGood();
                }
            }
        });
        viewBinding.closeFrom.setOnClickListener(v->{
            setVisibility(GONE);
        });

        //属性
        viewBinding.addGroup.setOnClickListener(v->{
            if(viewBinding.edittextGroup.getText().toString().isEmpty())
            {
                ToastUtils.info("名称不能为空!");
                return;
            }
            viewBinding.addGroup.setText("修改名称");
            if(ggids.isEmpty()&&!bpa_goodproperties.isEmpty()){
                ToastUtils.info("请选择属性");
                return;
            }

            BPA_GOODSRECIPENAME goodsrecipename = QueryDB.GetGoodsRecipeNameDesignId(ggids,goodsData.id);
            if(goodsrecipename!=null)
            {
                goodsrecipename.name = viewBinding.edittextGroup.getText().toString();
                goodsrecipename.design=ggids;
                goodsrecipename.goodsID=goodsData.id;
                QueryDB.UpdateGoodsRecipeName(goodsrecipename);
                ToastUtils.info("修改【"+goodsrecipename.name+"】配方成功");
            }else {
                goodsrecipename = new BPA_GOODSRECIPENAME();
                goodsrecipename.name = viewBinding.edittextGroup.getText().toString();
                goodsrecipename.design=ggids;
                goodsrecipename.goodsID=goodsData.id;
                QueryDB.AddGoodsRecipeName(goodsrecipename);
                ToastUtils.info("新建【"+goodsrecipename.name+"】配方成功");
            }
            //商品配方名称
            goodsrecipenames.clear();
            goodsrecipenames.addAll(QueryDB.GetGoodsRecipeNameGoodId(goodsData.id));
            groupAdapter.notifyDataSetChanged();
        });
    }

    BPA_GOODSRECIPENAME goodsrecipename = null;
    String ggids = "";//规格id集合
    String groupName ="";
    /**
     * 查询是否有配方
     */
    public boolean hasGroup() {
        //1.数据名称不能为空
        ggids = "";
        groupName ="";
        for (ResGoodProperty item : bpa_goodproperties) {
            for (ResGoodProperty k : item.child) {
                if (k.isSelect) {
                    ggids += k.id + ",";
                    groupName +="/"+k.name;
                }
            }
        }
        if(!groupName.isEmpty()&&groupName.length()>1){
            groupName = groupName.substring(1);
        }

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

        goodsrecipename = QueryDB.GetGoodsRecipeNameDesignId(ggids,goodsData.id);
        if (goodsrecipename == null) {
            return false;
        }
        return true;
    }

    /**
     * 属性信息
     */
    private ArrayList<ResGoodProperty> bpa_goodproperties = new ArrayList<>();
    private pfsx_adapter sxadapter;
    private void initPropertyData() {
        //2.填充规则数据，查询所有属性大类
        viewBinding.recyclerProperty.setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false));

        bpa_goodproperties.clear();
        ArrayList<ResGoodProperty> allGoodProperty = new ArrayList<>();
        ArrayList<BPA_GOODPROPERTY> da = QueryDB.GetGoodsPropertyALL("0");
        for (BPA_GOODPROPERTY item : da) {
            ResGoodProperty re = new ResGoodProperty();
            re.id = item.id;
            re.name = item.name;

            ArrayList<BPA_GOODPROPERTY> zsx = QueryDB.GetGoodsPropertyALL(item.id);
            re.child = new ArrayList<>();

            ArrayList<ResGoodProperty> _chid = new ArrayList<>();
            for (BPA_GOODPROPERTY k : zsx) {
                ResGoodProperty m = new ResGoodProperty();
                m.id = k.id;
                m.name = k.name;
                m.isSelect = false;
                _chid.add(m);
            }
            re.child = _chid;
            re.GoodsTypeId=item.GoodsTypeId;
            re.sort= item.sort;
            allGoodProperty.add(re);
        }
        for (ResGoodProperty pro:allGoodProperty)
        {
            if(pro.GoodsTypeId!=null && !pro.GoodsTypeId.isEmpty())
            {
                if(pro.GoodsTypeId.contains(goodsData.goodtype))
                {
                    bpa_goodproperties.add(pro);
                }
            }
        }


        List<String> idList = new ArrayList<>();
        for (ResGoodProperty item:bpa_goodproperties)
        {
            int i = 0;
            for (ResGoodProperty c : item.child) {
                c.isSelect = i == 0;
                if(i==0){
                    idList.add(c.id);
                }
                i++;
            }
        }
        LogUtils.d("idList = "+idList);
        sxadapter = new pfsx_adapter(getContext(),bpa_goodproperties);
        sxadapter.setClickCallBack(new pfsx_adapter.ItemClickCallBack() {
            @Override
            public void onClickItem(View view, int position, String attributeId) {
                if(hasGroup()){
                    viewBinding.addGroup.setText("修改名称");

                }else {
                    viewBinding.addGroup.setText("新建配方");
                }
                viewBinding.edittextGroup.setText(goodsData.name +(groupName.isEmpty()?"":("—"+groupName)));
            }
        });
        viewBinding.recyclerProperty.setAdapter(sxadapter);
        viewBinding.recyclerProperty.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(hasGroup()){
                    viewBinding.addGroup.setText("修改名称");
                }else {
                    viewBinding.addGroup.setText("新建配方");
                }
                viewBinding.edittextGroup.setText(goodsData.name +(groupName.isEmpty()?"":("—"+groupName)));
            }
        },200);
    }

    /**
     * 当前物料数据
     */
    private List<BPA_MATERIAL> materilasList=new ArrayList<>();
    private ArrayList<BPA_GOODSRECIPENAME> goodsrecipenames = new ArrayList<>();
    /**
     * 复制弹窗
     */
    private CopyRecipeDialog copyRecipeDialog;
    /**
     * 配方详情
     */
    private GoodGroupNameAdapter groupAdapter;
    private void initGroupDetail(){
        //物料数据
        materilasList.clear();
        materilasList.addAll(QueryDB.GetMaterialALL());
        //商品配方名称
        goodsrecipenames.clear();
        goodsrecipenames.addAll(QueryDB.GetGoodsRecipeNameGoodId(goodsData.id));

        groupAdapter = new GoodGroupNameAdapter() {
            @Override
            protected void onDelete(int position, BPA_GOODSRECIPENAME bean) {
                String title = "温馨提示！";
                String message = "客官确定要删除配方【"+bean.name+"】吗？";
                AlertDialogUtils.showDialog(getContext(), title, message, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        ArrayList<ResGoodsRecipe> re= QueryDB.GetGoodsSreciperecipeList(bean.id);
                        for(ResGoodsRecipe item:re)
                        {
                            QueryDB.DeleteGoodsSrecipe(item);
                        }
                        QueryDB.DeleteGoodsRecipeName(bean);
                        ToastUtils.info("删除成功");
                        KeyboardUtil.hideKeyboard(viewBinding.recyclerDetail);
                        goodsrecipenames.remove(position);
                        groupAdapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                });
            }

            @Override
            protected void onCopy(int position, BPA_GOODSRECIPENAME bean) {
                if(isFast2Click()){
                    ToastUtils.info("请勿快速点击！");
                    return;
                }
                 if(copyRecipeDialog == null){
                     copyRecipeDialog = new CopyRecipeDialog();
                 }
                Bundle bundle = new Bundle();
                bundle.putString("goodId", goodsData.id);
                copyRecipeDialog.setArguments(bundle);
                copyRecipeDialog.setmListener(new CopyRecipeDialog.ClickCallBack() {
                    @Override
                    public void onSubmit(BPA_GOODSRECIPENAME copyGoodsRecipe) {
                        ArrayList<ResGoodsRecipe> re= QueryDB.GetGoodsSreciperecipeList(bean.id);
                        for(ResGoodsRecipe item:re)
                        {
                            QueryDB.DeleteGoodsSrecipe(item);
                        }
                        List<BPA_GOODSRECIPE> data = new ArrayList<>();
                        ArrayList<ResGoodsRecipe> copys = QueryDB.GetGoodsSreciperecipeList(copyGoodsRecipe.id);
                        for(ResGoodsRecipe item:copys){
                            BPA_GOODSRECIPE bpaGoodsrecipe = new BPA_GOODSRECIPE();
                            bpaGoodsrecipe.sort = 0;
                            bpaGoodsrecipe.goodsID = item.goodsID;
                            bpaGoodsrecipe.recipeID = bean.id;
                            bpaGoodsrecipe.materialID = item.materialID;
                            bpaGoodsrecipe.value = item.value;
                            bpaGoodsrecipe.materialType = item.materialType;
                            bpaGoodsrecipe.processms = item.processms;
                            bpaGoodsrecipe.processname = item.processname;
                            bpaGoodsrecipe.processvalue = item.processvalue;
                            data.add(bpaGoodsrecipe);
                        }
                        QueryDB.AddGoodsSrecipeList(data);
                        ToastUtils.info("复制成功");
                        groupAdapter.notifyItemChanged(position);
                    }
                });
                copyRecipeDialog.show(activity.getSupportFragmentManager(),"复制配方");
            }
        };
        groupAdapter.setMaterilasList(materilasList);
        groupAdapter.setNewData(goodsrecipenames);
        viewBinding.recyclerDetail.setAdapter(groupAdapter);
    }

    /**
     * 判断重复点击
     */
    private long lastTime2;

    public boolean isFast2Click(){
        long curTime = System.currentTimeMillis();
        if(curTime - lastTime2 < 1000){
            return true;
        }
        lastTime2 = curTime;
        return false;
    }

    /**
     * 销毁
     */
    public void destroy(){
//        MessageManager.getInstance().unRegisterMessageReceiver(activity);
        EventBus.getDefault().unregister(this);
        goodsData = null;
        mListener = null;
        bpa_goodproperties.clear();
        bpa_goodproperties = null;
        materilasList.clear();
        materilasList = null;
        goodsrecipenames.clear();
        goodsrecipenames = null;
        viewBinding.recyclerDetail.setAdapter(null);
        if(groupAdapter!=null){
            groupAdapter = null;
        }
        url = null;
        viewBinding.recyclerProperty.setAdapter(null);
        if(sxadapter!=null){
            sxadapter = null;
        }
        activity = null;
    }
    private ChangeCallBack changeCallBack;

    public void setChangeCallBack(ChangeCallBack changeCallBack) {
        this.changeCallBack = changeCallBack;
    }

    public interface ChangeCallBack{
        void onChangeGood();
    }

    //接收图片选择事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImageSelectEvent(ImageUrlSelectEvent event){
        url=event.url;
        new MyBitmapUtils().disPlay(viewBinding.imgGoods,url);
        GlideUtil.showImage(viewBinding.imgGoods.getContext(),url,viewBinding.imgGoods,R.mipmap.loading3);
        goodsData.url = url;
        QueryDB.UpdateGoods(goodsData);
        if(changeCallBack!=null){
            changeCallBack.onChangeGood();
        }
    }
}
