package com.fujica.abk.component;

import com.fujica.abk.ResourceTable;
import com.fujica.abk.model.out.ParkNearRes;
import com.fujica.abk.utils.Log;
import com.fujica.abk.utils.ScreenUtil;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;

/**
 * 停车场列表项组件
 * 内部调用 API 并绑定数据
 */
public class ParkItemComponent extends DirectionalLayout {
    private ParkNearRes parkData;
    private String parkId;
    private Component rootLayout;
    private OnItemSelectedListener onItemSelectedListener;
    private boolean isSelected = false;

    /**
     * 选中状态监听器
     */
    public interface OnItemSelectedListener {
        void onItemSelected(ParkItemComponent component, ParkNearRes park);
        void onItemDeselected(ParkItemComponent component);
    }

    /**
     * 构造函数（通过 parkId 创建）
     */
    public ParkItemComponent(Context context, String parkId) {
        super(context);
        this.parkId = parkId;
        initComponent(context);
        loadParkData();
    }

    /**
     * 构造函数（通过 ParkNearRes 对象创建）
     */
    public ParkItemComponent(Context context, ParkNearRes park) {
        super(context);
        this.parkData = park;
        this.parkId = park != null ? park.getParkId() : null;
        initComponent(context);
        bindData();
    }

    /**
     * 初始化组件
     */
    private void initComponent(Context context) {
        // 设置布局属性
        setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);
        setOrientation(HORIZONTAL);
        setBackground(createNormalBackground());

        // 加载布局文件
        rootLayout = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_item_park, null, false);
        addComponent(rootLayout);

        // 设置整个列表项的点击事件
        setClickedListener(component -> {
            if (parkData != null) {
                // 如果已选中，则取消选中；否则选中
                if (isSelected) {
                    setSelected(false);
                    if (onItemSelectedListener != null) {
                        onItemSelectedListener.onItemDeselected(this);
                    }
                } else {
                    setSelected(true);
                    if (onItemSelectedListener != null) {
                        onItemSelectedListener.onItemSelected(this, parkData);
                    }
                }
            }
        });
    }

    /**
     * 加载停车场数据（通过 parkId）
     */
    private void loadParkData() {
//        if (parkId == null || parkId.isEmpty()) {
//            Log.error("parkId 为空，无法加载数据");
//            return;
//        }
//
//        // 调用 API 获取停车场详情
//        String url = "/park/detail?parkId=" + parkId;
//        CompletableFuture<R<Object>> future = api.http(getContext(), url, "GET", null, null, null);
//
//        future.thenAccept(response -> {
//            if (response == null || !response.isSuccess()) {
//                String errorMsg = response != null ? response.getMsg() : "请求失败";
//                Log.error("加载停车场数据失败: " + errorMsg);
//                return;
//            }
//
//            Object dataObj = response.getData();
//            if (dataObj == null) {
//                Log.error("响应数据为空");
//                return;
//            }
//
//            // 解析数据
//            ZSONObject parkObj;
//            if (dataObj instanceof ZSONObject) {
//                parkObj = (ZSONObject) dataObj;
//            } else {
//                parkObj = ZSONObject.stringToZSON(dataObj.toString());
//            }
//
//            if (parkData != null) {
//                // 在 UI 线程更新界面（使用 Component 的 postTask 方法）
//                new EventHandler(EventRunner.getMainEventRunner()).postTask(() -> {
//                    bindData();
//                }, 0);
//            }
//        });
    }

    /**
     * 绑定数据到 UI
     */
    private void bindData() {
        if (parkData == null || rootLayout == null) {
            return;
        }

        try {
            // 设置停车场名称
            Text nameText = (Text) rootLayout.findComponentById(ResourceTable.Id_park_name);
            if (nameText != null && parkData.getParkName() != null) {
                nameText.setText(parkData.getParkName());
            }

            // 设置距离和地址
            String distanceStr = parkData.getDistance() != null ?
                    String.format("%.1fkm", parkData.getDistance() / 1000.0) : "0km";
            String address = parkData.getAddress() != null ? parkData.getAddress() : "";
            ((Text) rootLayout.findComponentById(ResourceTable.Id_parking_address_1)).setText(distanceStr);
            ((Text) rootLayout.findComponentById(ResourceTable.Id_parking_address_2)).setText(" | " + address);

            // 设置总车位
            Text totalPlaceText = (Text) rootLayout.findComponentById(ResourceTable.Id_text_total_place);
            if (totalPlaceText != null && parkData.getTotalPlace() != null) {
                totalPlaceText.setText(String.valueOf(parkData.getTotalPlace()));
            }

            // 设置剩余车位
            Text residuePlaceText = (Text) rootLayout.findComponentById(ResourceTable.Id_text_residue_place);
            if (residuePlaceText != null && parkData.getResiduePlace() != null) {
                residuePlaceText.setText(String.valueOf(parkData.getResiduePlace()));
            }

            // 设置免费时长（从chargeInfo中解析，这里简化处理）
            ((Text) rootLayout.findComponentById(ResourceTable.Id_text_free_duration)).setText(parkData.getFreeTime() + "分");

            // 设置标签
            DirectionalLayout tagsContainer = rootLayout.findComponentById(ResourceTable.Id_tags_container);
            if (tagsContainer != null) {
                tagsContainer.removeAllComponents();

                // 根据数据添加标签
                if (parkData.getReservationEnable() != null && parkData.getReservationEnable() == 1) {
                    addTag(tagsContainer, "可预约", "#f1f7ff", "#3286FB");
                }
                if (parkData.getPowerEnable() != null && parkData.getPowerEnable() == 1) {
                    addTag(tagsContainer, "可充电", "#f3fffd","#29C2AC");
                }
            }

            // 设置导航按钮点击事件
            Image navButton = (Image) rootLayout.findComponentById(ResourceTable.Id_btn_navigate);
            if (navButton != null) {
                navButton.setClickedListener(component -> {
                    // 导航功能
                    Log.info("导航到: " + parkData.getParkName());
                    // TODO: 实现导航功能
                });
            }
        } catch (Exception e) {
            Log.error("绑定数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 添加标签
     */
    private void addTag(DirectionalLayout container, String text, String bgColor, String textColor) {
        Text tag = new Text(getContext());
        tag.setText(text);
        tag.setTextSize(ScreenUtil.fp2px(getContext(), 12));
        tag.setTextColor(new Color(Color.getIntColor(textColor)));
        tag.setPadding(ScreenUtil.vp2px(getContext(), 8), ScreenUtil.vp2px(getContext(), 4), 
                ScreenUtil.vp2px(getContext(), 8), ScreenUtil.vp2px(getContext(), 4));

        // 创建圆角背景
        ShapeElement background = new ShapeElement();
        background.setShape(ShapeElement.RECTANGLE);
        background.setRgbColor(parseColorToRgbColor(bgColor));
        background.setCornerRadius(ScreenUtil.vp2px(getContext(), 12));
        tag.setBackground(background);

        tag.setMarginLeft(ScreenUtil.vp2px(getContext(), 4));
        container.addComponent(tag);
    }

    /**
     * 创建普通背景
     */
    private ShapeElement createNormalBackground() {
        ShapeElement background = new ShapeElement();
        background.setShape(ShapeElement.RECTANGLE);
        RgbColor normalColor = parseColorToRgbColor("#FFFFFFFF");
        background.setRgbColor(normalColor);
        return background;
    }

    /**
     * 创建选中背景
     */
    private ShapeElement createSelectedBackground() {
        ShapeElement background = new ShapeElement();
        background.setShape(ShapeElement.RECTANGLE);
        RgbColor selectedColor = new RgbColor(255, 236, 230, 255);
        background.setRgbColor(selectedColor);
        return background;
    }

    /**
     * 设置选中状态
     */
    public void setSelected(boolean selected) {
        if (isSelected == selected) {
            return;
        }
        isSelected = selected;
        setBackground(selected ? createSelectedBackground() : createNormalBackground());
    }

    /**
     * 获取选中状态
     */
    public boolean isSelected() {
        return isSelected;
    }

    /**
     * 设置选中监听器
     */
    public void setOnItemSelectedListener(OnItemSelectedListener listener) {
        this.onItemSelectedListener = listener;
    }

    /**
     * 获取停车场数据
     */
    public ParkNearRes getParkData() {
        return parkData;
    }

    /**
     * 将颜色字符串解析为 RgbColor
     * 支持格式: #RGB, #RRGGBB, #AARRGGBB
     */
    private RgbColor parseColorToRgbColor(String colorStr) {
        if (colorStr == null || colorStr.isEmpty()) {
            return new RgbColor(255, 255, 255, 255); // 默认白色
        }

        // 移除 # 号
        String color = colorStr.startsWith("#") ? colorStr.substring(1) : colorStr;

        int alpha = 255;
        int red, green, blue;

        if (color.length() == 3) {
            // #RGB 格式，每个字符重复一次
            red = Integer.parseInt(color.substring(0, 1) + color.substring(0, 1), 16);
            green = Integer.parseInt(color.substring(1, 2) + color.substring(1, 2), 16);
            blue = Integer.parseInt(color.substring(2, 3) + color.substring(2, 3), 16);
        } else if (color.length() == 6) {
            // #RRGGBB 格式
            red = Integer.parseInt(color.substring(0, 2), 16);
            green = Integer.parseInt(color.substring(2, 4), 16);
            blue = Integer.parseInt(color.substring(4, 6), 16);
        } else if (color.length() == 8) {
            // #AARRGGBB 格式
            alpha = Integer.parseInt(color.substring(0, 2), 16);
            red = Integer.parseInt(color.substring(2, 4), 16);
            green = Integer.parseInt(color.substring(4, 6), 16);
            blue = Integer.parseInt(color.substring(6, 8), 16);
        } else {
            // 无效格式，返回默认白色
            return new RgbColor(255, 255, 255, 255);
        }

        return new RgbColor(red, green, blue, alpha);
    }
}

