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

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
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_GOODSRECIPENAME;
import com.bonait.bnframework.common.db.mode.BPA_ORDER;
import com.bonait.bnframework.common.db.mode.BPA_SUBORDER;
import com.bonait.bnframework.common.db.res.ResGoodProperty;
import com.bonait.bnframework.common.helper.WrapContentLinearLayoutManager;
import com.bonait.bnframework.common.utils.DisplayManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.databinding.DialogAddMakegoodBinding;
import com.bonait.bnframework.modules.home.adapter.pfsx_adapter;

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

import butterknife.ButterKnife;

/**
 * @author: liup
 * @description: 复制配方
 * @date: 2024/6/7 13:56.
 */
public class CopyRecipeDialog extends DialogFragment {
    private DialogAddMakegoodBinding viewBinding;
    private BPA_GOODS Good;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.DialogScale);
        if(getArguments()!=null){
            String goodId = getArguments().getString("goodId");
            Good = QueryDB.GetGoodsId(goodId);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewBinding = DialogAddMakegoodBinding.inflate(inflater,container,false);
        ButterKnife.bind(this, viewBinding.getRoot());
        DisplayManager.scaleViewGroup(viewBinding.getRoot());
        return viewBinding.getRoot();
    }



    @Override
    public void onStart() {
        super.onStart();
        if(getDialog()!=null){
            Window window = getDialog().getWindow();
            assert window != null;
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.CENTER;
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.MATCH_PARENT;
            window.setAttributes(params);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    ArrayList<ResGoodProperty> bpa_goodproperties = new ArrayList<>();
    private pfsx_adapter sxadapter;

    private void initView() {
        viewBinding.quzhizuo.setText("复制");
        viewBinding.makegoodtitle.setText(Good.name+"");
        //2.填充规则数据，查询所有属性大类
        viewBinding.datatabMakesx.setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false));

        ArrayList<BPA_GOODSRECIPENAME> goodsrecipenames = QueryDB.GetGoodsRecipeNameGoodId(Good.id);
        assert goodsrecipenames != null;
        LogUtils.d("add_makegood_control goodsrecipenames = "+goodsrecipenames.size());
        List<String> attributeNameList = new ArrayList<>();
        for(BPA_GOODSRECIPENAME goodsrecipename1 : goodsrecipenames){
            if(goodsrecipename1.design.contains(",")){
                String[] res = goodsrecipename1.design.split(",");
                attributeNameList.addAll(Arrays.asList(res));
            }else {
                attributeNameList.add(goodsrecipename1.design);
            }
        }

        bpa_goodproperties.clear();
        ArrayList<BPA_GOODPROPERTY> parentAttributes = QueryDB.GetGoodsPropertyByTypeId(Good.goodtype);
        for(BPA_GOODPROPERTY bpaGoodproperty : parentAttributes ){
            ArrayList<BPA_GOODPROPERTY> zsx= QueryDB.GetGoodsPropertyALL(bpaGoodproperty.id);
            ArrayList<ResGoodProperty> childList = new ArrayList<>();
            for(BPA_GOODPROPERTY bean:zsx){
                if(attributeNameList.contains(bean.id)){
                    ResGoodProperty child = new ResGoodProperty();
                    child.id = bean.id;
                    child.name = bean.name;
                    child.foreignKeyRe = bean.foreignKeyRe;
                    child.parentid = bpaGoodproperty.id;
                    child.sort = bean.sort;
                    child.GoodsTypeId = bean.GoodsTypeId;
                    child.isSelect = false;
                    childList.add(child);
                }
            }
            if(!childList.isEmpty()){
                ResGoodProperty resGoodProperty = new ResGoodProperty();
                resGoodProperty.id = bpaGoodproperty.id;
                resGoodProperty.name = bpaGoodproperty.name;
                resGoodProperty.foreignKeyRe = bpaGoodproperty.foreignKeyRe;
                resGoodProperty.parentid = "";
                resGoodProperty.sort = bpaGoodproperty.sort;
                resGoodProperty.GoodsTypeId = bpaGoodproperty.GoodsTypeId;
                resGoodProperty.isSelect = false;
                resGoodProperty.child = new ArrayList<>(childList);
                bpa_goodproperties.add(resGoodProperty);
            }

        }

        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.setIdList(idList);
//        sxadapter.setGoodId(Good.id);
        sxadapter.setClickCallBack(new pfsx_adapter.ItemClickCallBack() {
            @Override
            public void onClickItem(View view, int position, String attributeId) {
//                idList.set(position,attributeId);
//                for(int i=0;i<bpa_goodproperties.size();i++){
//                    if(i!=position){
//                        sxadapter.setIdList(idList);
//                        sxadapter.notifyItemChanged(i);
//                    }
//                }
                if(DataValidation()){
                    viewBinding.quzhizuo.setText("确定复制");
                    viewBinding.quzhizuo.setBackgroundDrawable(getResources().getDrawable(R.drawable.button3));
                }else {
                    viewBinding.quzhizuo.setText("不存在配方,无法复制");
                    viewBinding.quzhizuo.setBackgroundDrawable(getResources().getDrawable(R.drawable.button4));
                }
                String title = Good.name;
                if(!names.isEmpty()){
                    title = Good.name+"—"+names;
                }
                viewBinding.makegoodtitle.setText(title);
            }
        });
        viewBinding.datatabMakesx.setAdapter(sxadapter);
        viewBinding.datatabMakesx.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(DataValidation()){
                    viewBinding.quzhizuo.setText("确定复制");
                    viewBinding.quzhizuo.setBackgroundDrawable(getResources().getDrawable(R.drawable.button3));
                }else {
                    viewBinding.quzhizuo.setText("不存在配方,无法复制");
                    viewBinding.quzhizuo.setBackgroundDrawable(getResources().getDrawable(R.drawable.button4));
                }
                String title = Good.name;
                if(!names.isEmpty()){
                    title = Good.name+"—"+names;
                }
                viewBinding.makegoodtitle.setText(title);
            }
        },100);
        initEvent();
    }

    private void initEvent() {
        viewBinding.quzhizuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!DataBus.getInstance().doubleClick()) {
                    if (mListener != null && SaveData()) {
                        mListener.onSubmit(goodsrecipename);
                    }
                }
            }
        });
        viewBinding.closeFromGood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    /**
     * 保存数据
     */
    private boolean SaveData() {
        if (DataValidation()) {

            BPA_ORDER order = new BPA_ORDER();
            order.thirdPartyID = "手动下单";
            order.status = 0;
            order.deviceID = ConfigName.getInstance().DeviceId;
            order.userID = ConfigName.getInstance().user.userID;
            QueryDB.AddOrder(order);

            BPA_SUBORDER suborder = new BPA_SUBORDER();
            suborder.deviceID = ConfigName.getInstance().DeviceId;
            suborder.userID = ConfigName.getInstance().user.userID;
            suborder.orderID = order.id;
            suborder.goodsID = ((BPA_GOODS) Good).id;
            suborder.recipeID=goodsrecipename.id;
            suborder.number = 1;
            suborder.status = 0;
            suborder.exp=names;
            QueryDB.AddSubOrder(suborder);

            DataBus.getInstance().AddGoodsMake(suborder);
            ToastUtils.info("商品:"+Good.name+",加入队列中...");
            return true;
        }else
        {
            ToastUtils.info("没有查询到配方,不能制作!");
            return false;
        }
    }

    BPA_GOODSRECIPENAME goodsrecipename = null;
    String ggids = "";//规格id集合
    String names="";
    /**
     * 数据验证
     */
    private boolean DataValidation() {
        //1.数据名称不能为空
        ggids = "";names="";
        for (ResGoodProperty item : bpa_goodproperties) {
            for (ResGoodProperty k : item.child) {
                if (k.isSelect) {
                    ggids += k.id + ",";
                    names+="/"+k.name;
                }
            }
        }
        if(!names.isEmpty()&& names.length()>1){
            names = names.substring(1);
        }

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

        goodsrecipename = QueryDB.GetGoodsRecipeNameDesignId(ggids,Good.id);
        if (goodsrecipename == null) {
//            ToastUtils.info("没有查询到配方,不能制作!");
            return false;
        }
        return true;
    }
    private ClickCallBack mListener;

    public void setmListener(ClickCallBack mListener) {
        this.mListener = mListener;
    }

    public interface ClickCallBack{
        void onSubmit(BPA_GOODSRECIPENAME copyGoodsRecipe);
    }
}
