package com.unibuy.smartdevice.ui.devs.vmc;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.CloneUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.google.common.reflect.TypeToken;
import com.unibuy.smartdevice.FragmentAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.databinding.FragmentVmcBinding;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.SaleFlowHandler;


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

public class VmcFragment extends FragmentAbstract {
    public enum Option {
        TOAST(0),
        SHIPPED_PRODUCT(1),
        ADD_PRODUCT_OPEN(3),
        ADD_PRODUCT_CLOSE(4),
        ADD_PRODUCT_FREE_GIFT(5),
        DECRYPTION_ERROR(6),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    private FragmentVmcBinding binding;
    private List<SlotStructure> slotList;
    private List<Integer> sizeList;
    private RecyclerVmcBuyListAdpter recyclerVmcBuyListAdpter;

    @Override
    protected String setName() {
        return "智販機";//智販機
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                getLogs().info("commandCode:" + commandCode);
                Option option = optionMap.get(commandCode);

                switch (option) {
                    case TOAST:
                        super.execute(context, commandCode, message);
                        break;
                    case SHIPPED_PRODUCT:
                        recyclerVmcBuyListAdpter.notifyItemRangeChanged(0, slotList.size());
                        break;
                    case ADD_PRODUCT_OPEN:
                        if (!MyApp.getInstance().getBuyList().isEmpty()) {
                            sizeList.clear();
                            for (int index = 0; index < slotList.size(); index++) {
                                SlotStructure slotData = slotList.get(index);
                                int count = slotData.getCount();
                                sizeList.add(index, count);

                                for (int i = 0; i < MyApp.getInstance().getBuyList().size(); i++) {
                                    BuyStructure buyData = MyApp.getInstance().getBuyList().get(i);
                                    if (buyData.getField() == slotData.getField() && buyData.getSlot() == slotData.getSlot()) {
                                        int slot = buyData.getSlot();
                                        int count2 = buyData.getCount();
                                        count = count - count2;
                                    }
                                }

                                slotData.setCount(count);

                                recyclerVmcBuyListAdpter.notifyItemChanged(index);
                            }
                        }
                        break;
                    case ADD_PRODUCT_CLOSE:
                        if (!sizeList.isEmpty()) {
                            for (int index = 0; index < slotList.size(); index++) {
                                int count = sizeList.get(index);

                                SlotStructure slotData = slotList.get(index);
                                slotData.setCount(count);

                                recyclerVmcBuyListAdpter.notifyItemChanged(index);
                            }
                            sizeList.clear();
                        }
                        break;
                    case ADD_PRODUCT_FREE_GIFT:
                        break;
                    case DECRYPTION_ERROR:
                        super.execute(context, commandCode, "@掃碼失敗，請再掃描一次");
                        break;
                }
            }
        };
    }

    public VmcFragment() {
        super(null);
    }

    public VmcFragment(HandlerMain srcHandlerMain) {
        super(srcHandlerMain);
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        VmcViewModel vmcViewModel = new ViewModelProvider(this).get(VmcViewModel.class);
        binding = FragmentVmcBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        slotList = new ArrayList<>();
        sizeList = new ArrayList<>();
        /* 這一段程式是在銷售平台的商品畫面呈現程式 */
        recyclerVmcBuyListAdpter = new RecyclerVmcBuyListAdpter(this, slotList);
        binding.recyclerBuy.setAdapter(recyclerVmcBuyListAdpter);
        binding.recyclerBuy.setLayoutManager(new GridLayoutManager(getContext(), 3));

//        for (int i = 0; i < MyApp.getInstance().getSlotList(SlotField.VMC.getField()).size(); i++) {
//            SlotStructure slot = MyApp.getInstance().getSlotList(SlotField.VMC.getField()).get(i);
//            if (!slot.getProduct().getProductID().isEmpty() && !slot.getProduct().getProductName().isEmpty() && slot.getProduct().getSellingPrice() > 0) {
//                slotList.add(slot);
//            }
//        }

//        boolean isHave = false;
//        for (int i = 0; i < MyApp.getInstance().getSlotList(SlotField.VMC.getField()).size(); i++) {
//            SlotStructure slot = MyApp.getInstance().getSlotList(SlotField.VMC.getField()).get(i);
//            if (!slot.getProduct().getProductID().isEmpty() && !slot.getProduct().getProductName().isEmpty() && slot.getProduct().getSellingPrice() > 0) {
//                for(int j = 0; j < slotList.size(); j++){
//                    if(slotList.get(j).getProduct().getProductID().equals(slot.getProduct().getProductID())){
//                        isHave = true;
//                    }
//                }
//                if(!isHave) {
//                    slotList.add(slot);
//                    isHave = false;
//                }else{
//                    isHave = false;
//                }
//            }
//        }
//
//        if (!slotList.isEmpty()) {
//            recyclerVmcBuyListAdpter.notifyItemInserted(slotList.size() - 1);
//        }

//        // 🔹 用 Map 做去重 + 合併
//        Map<String, SlotStructure> uniqueProductMap = new HashMap<>();
//
//        for (SlotStructure slot : MyApp.getInstance().getSlotList(SlotField.VMC.getField())) {
//            if (slot.getProduct() == null) continue;
//            if (slot.getProduct().getProductID().isEmpty() ||
//                    slot.getProduct().getProductName().isEmpty() ||
//                    slot.getProduct().getSellingPrice() <= 0) {
//                continue; // 過濾無效商品
//            }
//
//            String productId = slot.getProduct().getProductID();
//            SlotStructure existing = uniqueProductMap.get(productId);
//
//            if (existing == null) {
//                // 先放第一個
//                uniqueProductMap.put(productId, slot);
//            } else {
//                // 合併數量
//                int newCount = existing.getCount() + slot.getCount();
//
//                // 如果第一個貨道數量是 0，且這個 slot 有貨，就換成這個 slot
//                if (existing.getCount() == 0 && slot.getCount() > 0) {
//                    slot.setCount(newCount);
//                    uniqueProductMap.put(productId, slot);
//                } else {
//                    existing.setCount(newCount);
//                    uniqueProductMap.put(productId, existing);
//                }
//            }
//        }
//
//        // 更新 UI list
//        slotList.clear();
//        slotList.addAll(uniqueProductMap.values());
//        recyclerVmcBuyListAdpter.notifyDataSetChanged();

        if (isUseStartOnSwitchFragment()) {
            startOnSwitchFragment();
            setUseStartOnSwitchFragment(false);
        }

        // 解決生命週期時序競爭：VmcFragment 視圖加載完成後重新綁定大掃碼按鈕
        if (getActivity() instanceof FontendActivity) {
            com.unibuy.smartdevice.ui.SaleFlowHandler handler = ((FontendActivity) getActivity()).getSaleFlowHandler();
            if (handler != null) {
                handler.onSetupUI(root);
            }
        }

        return root;

    }

    /**
     * 刷新UI显示的商品列表
     * 1. 过滤无效商品数据
     * 2. 按ProductID分组并合并数量
     * 3. 更新UI显示
     */
    @SuppressLint("NewApi")
    public void updateFlowerBuyList() {
        if (recyclerVmcBuyListAdpter == null) return;
        ThreadUtils.runOnUiThread(()  -> {
            // 1. 获取原始数据（深拷贝）
            List<SlotStructure> rawSlots = CloneUtils.deepClone(
                    MyApp.getInstance().getSlotList(SlotField.VMC.getField()),
                    new TypeToken<List<SlotStructure>>() {}.getType()
            );
            if (rawSlots == null || rawSlots.isEmpty())  return;
            // 2. 处理数据（确保不修改任何对象）
            Map<String, SlotStructure> uniqueProductMap = new LinkedHashMap<>();
            for (SlotStructure slot : rawSlots) {
                ProductStructure product = slot.getProduct();
                if (isInvalidProduct(product)) continue;

                String productId = product.getProductID();
                SlotStructure existingSlot = uniqueProductMap.get(productId);

                if (existingSlot == null) {
                    // 直接使用拷贝后的 slot（避免修改）
                    uniqueProductMap.put(productId,  slot);
                } else {
                    // 數量累加
                    int newCount = existingSlot.getCount() + slot.getCount();

                    // 判斷代表 slot：如果 existingSlot 數量是 0，而這個 slot 有貨，就換掉
                    if (existingSlot.getCount() == 0 && slot.getCount() > 0) {
                        SlotStructure newSlot = CloneUtils.deepClone(slot, SlotStructure.class);
                        newSlot.setCount(newCount);
                        uniqueProductMap.put(productId, newSlot);
                    } else {
                        // 否則保留原本的貨道，只更新數量
                        SlotStructure newSlot = CloneUtils.deepClone(existingSlot, SlotStructure.class);
                        newSlot.setCount(newCount);
                        uniqueProductMap.put(productId, newSlot);
                    }
                }
            }
            // 3. 更新UI
            if (!uniqueProductMap.isEmpty())  {
                slotList.clear();
                slotList.addAll(uniqueProductMap.values());
                recyclerVmcBuyListAdpter.notifyDataSetChanged();
            }
        });
    }

    // 检查是否为无效商品
    private boolean isInvalidProduct(ProductStructure product) {
        return product == null
                || product.getProductID().isEmpty()
                || product.getProductName().isEmpty()
                || product.getSellingPrice() < 0;
    }

    @Override
    public void startOnSwitchFragment() { updateFlowerBuyList(); }

    @Override
    public void stopOnSwitchFragment() {

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}