package com.fujica.abk.utils;

import com.fujica.abk.ResourceTable;
import com.fujica.abk.model.response.ParkNearRes;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.utils.zson.ZSONObject;

import java.util.concurrent.CompletableFuture;

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

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

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

    /**
     * 构造函数（通过 ParkNearRes 对象创建）
     */
    public ParkingItemComponent(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_parking, null, false);
        addComponent(rootLayout);

        // 设置整个列表项的点击事件
        setClickedListener(component -> {
            if (parkData != null) {
                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);
            }
        });
    }

    /**
     * 解析停车场数据
     */
    private ParkNearRes parseParkData(ZSONObject parkObj) {
        try {
            ParkNearRes park = new ParkNearRes();
            if (parkObj.containsKey("parkId")) {
                park.setParkId(parkObj.getString("parkId"));
            }
            if (parkObj.containsKey("parkName")) {
                park.setParkName(parkObj.getString("parkName"));
            }
            if (parkObj.containsKey("isreserver")) {
                park.setIsreserver(parkObj.getIntValue("isreserver"));
            }
            if (parkObj.containsKey("isfindcar")) {
                park.setIsfindcar(parkObj.getIntValue("isfindcar"));
            }
            if (parkObj.containsKey("powerEnable")) {
                park.setPowerEnable(parkObj.getIntValue("powerEnable"));
            }
            if (parkObj.containsKey("distance")) {
                park.setDistance(parkObj.getDoubleValue("distance"));
            }
            if (parkObj.containsKey("address")) {
                park.setAddress(parkObj.getString("address"));
            }
            if (parkObj.containsKey("totalPlace")) {
                park.setTotalPlace(parkObj.getIntValue("totalPlace"));
            }
            if (parkObj.containsKey("residuePlace")) {
                park.setResiduePlace(parkObj.getIntValue("residuePlace"));
            }
            if (parkObj.containsKey("latitude")) {
                park.setLatitude(parkObj.getDoubleValue("latitude"));
            }
            if (parkObj.containsKey("longitude")) {
                park.setLongitude(parkObj.getDoubleValue("longitude"));
            }
            if (parkObj.containsKey("onlinePayEnable")) {
                park.setOnlinePayEnable(parkObj.getIntValue("onlinePayEnable"));
            }
            if (parkObj.containsKey("invoiceEnable")) {
                park.setInvoiceEnable(parkObj.getIntValue("invoiceEnable"));
            }
            if (parkObj.containsKey("reductionEnable")) {
                park.setReductionEnable(parkObj.getIntValue("reductionEnable"));
            }
            if (parkObj.containsKey("chargeInfo")) {
                park.setChargeInfo(parkObj.getString("chargeInfo"));
            }
            return park;
        } catch (Exception e) {
            Log.error("解析停车场数据失败: " + e.getMessage());
            return null;
        }
    }

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

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

            // 设置距离和地址
            Text addressText = (Text) rootLayout.findComponentById(ResourceTable.Id_parking_address);
            if (addressText != null) {
                String distanceStr = parkData.getDistance() != null ?
                        String.format("%.1fkm", parkData.getDistance() / 1000.0) : "0km";
                String address = parkData.getAddress() != null ? parkData.getAddress() : "";
                addressText.setText(distanceStr + " | " + 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 freeDurationText = (Text) rootLayout.findComponentById(ResourceTable.Id_text_free_duration);
            if (freeDurationText != null) {
                // 这里可以根据chargeInfo解析免费时长，暂时显示"15分"
                freeDurationText.setText("15分");
            }

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

                // 根据数据添加标签
                if (parkData.getIsreserver() != null && parkData.getIsreserver() == 1) {
                    addTag(tagsContainer, "可预约", "#4CAF50");
                }
                if (parkData.getPowerEnable() != null && parkData.getPowerEnable() == 1) {
                    addTag(tagsContainer, "可充电", "#4CAF50");
                }
                if (parkData.getReductionEnable() != null && parkData.getReductionEnable() == 1) {
                    addTag(tagsContainer, "惠", "#FF0000");
                }
            }

            // 设置导航按钮点击事件
            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) {
        Text tag = new Text(getContext());
        tag.setText(text);
        tag.setTextSize(11);
        tag.setTextColor(Color.WHITE);
        tag.setPadding(8, 4, 8, 4);

        // 创建圆角背景
        ShapeElement background = new ShapeElement();
        background.setShape(ShapeElement.RECTANGLE);
        RgbColor rgbColor = new RgbColor(Color.getIntColor(bgColor));
        background.setRgbColor(rgbColor);
        background.setCornerRadius(12);
        tag.setBackground(background);

        tag.setMarginLeft(4);
        container.addComponent(tag);
    }

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

    /**
     * 创建选中背景
     */
    private ShapeElement createSelectedBackground() {
        ShapeElement background = new ShapeElement();
        background.setShape(ShapeElement.RECTANGLE);
        RgbColor selectedColor = new RgbColor(255, 236,230, 255);
        background.setRgbColor(selectedColor);
        background.setCornerRadius(8);
        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;
    }
}

