package com.fujica.abk.component;

import com.fujica.abk.ResourceTable;
import com.fujica.abk.model.out.OrderDetailRes;
import com.fujica.abk.model.out.OrderRes;
import com.fujica.abk.utils.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.app.Context;

import java.text.DecimalFormat;

/**
 * 订单详情组件
 */
public class OrderDetailComponent extends DirectionalLayout {
    private Component rootLayout;
    private OrderDetailRes orderData;

    private Integer bizType;

    /**
     * 构造函数
     */
    public OrderDetailComponent(Context context) {
        super(context);
        initComponent(context);
    }

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

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

    /**
     * 设置订单数据并更新UI
     * @param order 订单基本信息
     * @param context 上下文对象，用于发起网络请求
     */
    public void setOrderData(OrderRes order, Context context) {
        if (order == null || order.getOrderId() == null) {
            Log.error("订单数据或订单ID为空");
            return;
        }

        // 根据业务类型调用不同的API获取详细数据
        String apiUrl;
        bizType = order.getBizType() != null ? order.getBizType() : 1;
        
        if (bizType == 2) {
            // 月卡订单
            apiUrl = "/order/cardLongLease/detail/" + order.getOrderId();
        } else {
            // 临停订单
            apiUrl = "/order/parking/detail/" + order.getOrderId();
        }

        // 创建API请求选项
        ApiOption apiOption = new ApiOption(apiUrl);
        apiOption.setMethod(ApiOption.GET);

        // 发起异步请求获取订单详情
        api.http(context, apiOption, new TypeToken<R<OrderDetailRes>>() {})
            .thenAccept(result -> {
                if (result.isSuccess() && result.getData() != null) {


//月卡缴费                    {"code":0,"msg":null,"data":{"id":"1790350398549020672","projectNo":"1","projectName":null,"parkId":"11111111112","parkName":null,"customerNo":"123","customerName":"张三","customerPhone":null,"departmentName":null,"houseInfo":null,"plateNo":"粤B123470,粤B123471","longLeaseId":1790350384393244672,"cardId":"eee3e109dd7f40e3baf4ea61d87f20bd","cardNo":null,"credentialType":0,"credentialTypeName":"车牌","cardTypeCode":"301","cardTypeName":"月卡A","cardTypeCategory":3,"cardTypeCategoryName":"长租","period":null,"cardUnitPrice":500,"cardTypeUnitPrice":null,"parkingLot":null,"cardCopies":1,"amountReceivable":5.00,"amount":0.01,"beforeExpireTime":null,"startTime":"2024-05-14","endTime":"2024-06-13","renewSource":4,"renewSourceName":"线上","paymentChannel":"6","paymentSource":"100","paymentWay":"5","paymentWayName":null,"orderId":"1821521232885862400","merchantOrderId":null,"renewStatus":1,"effectived":1,"invoiceStatus":"0.0","invoiceTime":null,"invoiceUrl":null,"extendJson":null,"createName":"system","paySuccessTime":null,"createTime":null,"remark":null,"carList":[]},"success":true,"reqId":"8ed257d59b814269abd8af11b995a74b"}

                    // 请求成功，更新订单数据
                    this.orderData = result.getData();

                    // 在主线程更新UI
                    context.getUITaskDispatcher().asyncDispatch(() -> {
                        bindData();
                    });
                } else {
                    Toast.error(context,"获取订单详情失败: " + (result.getMsg() != null ? result.getMsg() : "未知错误"));
                    // 如果请求失败，仍然使用传入的基本订单数据
                    Gson gson = new Gson();
                    this.orderData = gson.fromJson(gson.toJson(order), new TypeToken<OrderDetailRes>(){});
                    context.getUITaskDispatcher().asyncDispatch(() -> {
                        bindData();
                    });
                }
            })
            .exceptionally(throwable -> {
                Log.error("获取订单详情异常: " + throwable.getMessage());
                // 出现异常时，使用传入的基本订单数据
                Gson gson = new Gson();
                this.orderData = gson.fromJson(gson.toJson(order), new TypeToken<OrderDetailRes>(){});
                context.getUITaskDispatcher().asyncDispatch(() -> {
                    bindData();
                });
                return null;
            });
    }

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

        try {
            DecimalFormat df = new DecimalFormat("0.00");

            // 设置顶部总金额
            Text totalAmountText = (Text) rootLayout.findComponentById(ResourceTable.Id_detail_total_amount);
            if (totalAmountText != null) {
                if (bizType == 2) {
                    // 月卡显示元为单位
                    double amount = orderData.getAmount() != null ? orderData.getAmount() : 0.0;
                    totalAmountText.setText(df.format(amount));
                } else {
                    // 临停显示分转元
                    double amount = orderData.getActualAmount() != null ? orderData.getActualAmount() / 100.0 : 0.0;
                    totalAmountText.setText("￥" + df.format(amount));
                }
            }

            // 设置车牌号码
            setText(ResourceTable.Id_detail_plate_no, orderData.getPlateNo());
//            12-18 09:07:45.535 8407-8734/com.fujica.abk E 00000/fspark log: 响应：{"code":0,"msg":null,"data":{"total":12,"pages":2,"current":1,"size":10,"records":[{"id":1821521232998600704,"payNo":"0276c1c8b9564d6e8cd397add899f719","orderId":"1821521232885862400","parkId":"424063652937797","projectNo":"P20240709720098","goodsName":"停车费-月卡","bizType":2,"bizTypeStr":"月卡续费","totalAmount":0.01,"actualAmount":0.01,"discountAmount":0.00,"freeAmount":0.00,"payStatus":2,"paySuccessTime":"2024-08-08 20:18:02","callbackTime":"2024-08-08 20:18:03","description":"车主在线续费月卡","timeExpire":1723119658831,"userCode":"oq5PA6YFGAqRhTuipxFpZNK_EN04","payChannelId":1803701667564523111,"payChannelCode":"WX","payChannel":"微信","paySourceCode":"QR_Inside","paySource":"场内码","payWayCode":"WX","payWay":"微信","paySceneCode":"WX_JS","remark":null,"parkName":"测试车场0731","projectName":null,"createTime":"2024-08-08 20:17:58","createName":null,"updateTime":"2024-08-08 20:18:03","updateName":null},{"id":1821518463138959360,"payNo":"353a7aab182642968bf63cdc1195
            // 设置车场名称
            setText(ResourceTable.Id_detail_park_name, orderData.getParkName());

            // 根据订单类型显示不同字段
            if (bizType == 2) {
                // 月卡订单
                bindMonthlyCardData(df);
            } else {
                // 临停订单
                bindParkingData(df);
            }

            // 设置订单类型
            String orderType = bizType == 2 ? "月卡续费" : "停车缴费";
            setText(ResourceTable.Id_detail_order_type, orderType);

            // 设置支付时间
            String payTime = orderData.getPaySuccessTime() != null ? orderData.getPaySuccessTime() : 
                            (orderData.getPaySuccessTimeStr() != null ? orderData.getPaySuccessTimeStr() : "--");
            setText(ResourceTable.Id_detail_pay_time, payTime);

            // 设置支付方式
            String payWay = bizType == 2 ? orderData.getPaymentWayName() : orderData.getPayWayName();
            setText(ResourceTable.Id_detail_pay_way, payWay);

            // 设置订单号
            setText(ResourceTable.Id_detail_order_id, orderData.getOrderId());

            // 设置发票状态
            bindInvoiceStatus();

        } catch (Exception e) {
            Log.error("绑定订单详情数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 绑定临停订单数据
     */
    private void bindParkingData(DecimalFormat df) {
        // 显示临停相关字段
        setVisibility(ResourceTable.Id_layout_in_time, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_stay_time, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_total_fee, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_discount, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_actual_amount, Component.VISIBLE);

        // 隐藏月卡相关字段
        setVisibility(ResourceTable.Id_layout_parking_lot, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_card_type, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_card_price, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_card_copies, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_renew_duration, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_before_expire, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_start_time, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_end_time, Component.HIDE);

        // 设置临停数据
        setText(ResourceTable.Id_detail_in_time, orderData.getInTimeStr());
        setText(ResourceTable.Id_detail_stay_time, orderData.getStayTime());
        
        // 停车费（分转元）
        double totalFee = orderData.getTotalAmount() != null ? orderData.getTotalAmount() / 100.0 : 0.0;
        setText(ResourceTable.Id_detail_total_fee, "￥" + df.format(totalFee));
        
        // 优惠金额（分转元）
        double discount = orderData.getDiscountAmount() != null ? orderData.getDiscountAmount() / 100.0 : 0.0;
        setText(ResourceTable.Id_detail_discount, "￥" + df.format(discount));
        
        // 实付金额（分转元）
        double actualAmount = orderData.getActualAmount() != null ? orderData.getActualAmount() / 100.0 : 0.0;
        setText(ResourceTable.Id_detail_actual_amount, "￥" + df.format(actualAmount));
    }

    /**
     * 绑定月卡订单数据
     */
    private void bindMonthlyCardData(DecimalFormat df) {
        // 隐藏临停相关字段
        setVisibility(ResourceTable.Id_layout_in_time, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_stay_time, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_total_fee, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_discount, Component.HIDE);
        setVisibility(ResourceTable.Id_layout_actual_amount, Component.HIDE);

        // 显示月卡相关字段
        setVisibility(ResourceTable.Id_layout_parking_lot, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_card_type, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_card_price, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_card_copies, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_renew_duration, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_before_expire, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_start_time, Component.VISIBLE);
        setVisibility(ResourceTable.Id_layout_end_time, Component.VISIBLE);

        // 设置月卡数据
        setText(ResourceTable.Id_detail_parking_lot, 
                orderData.getParkingLot() != null ? orderData.getParkingLot().toString() : "--");
        setText(ResourceTable.Id_detail_card_type, orderData.getCardTypeName());
        setText(ResourceTable.Id_detail_card_price, orderData.getCardTypeUnitPrice());
        setText(ResourceTable.Id_detail_card_copies, 
                orderData.getCardCopies() != null ? orderData.getCardCopies().toString() : "--");
        
        // 续费时长 = 购买数量 * 周期
        int cardCopies = orderData.getCardCopies() != null ? orderData.getCardCopies() : 0;
        int period = orderData.getPeriod() != null ? orderData.getPeriod() : 0;
        setText(ResourceTable.Id_detail_renew_duration, String.valueOf(cardCopies * period));
        
        setText(ResourceTable.Id_detail_before_expire, orderData.getBeforeExpireTime());
        setText(ResourceTable.Id_detail_start_time, orderData.getStartTime());
        setText(ResourceTable.Id_detail_end_time, orderData.getEndTime());
    }

    /**
     * 绑定发票状态
     */
    private void bindInvoiceStatus() {
        Text invoiceStatusText = (Text) rootLayout.findComponentById(ResourceTable.Id_detail_invoice_status);
        Image invoiceArrow = (Image) rootLayout.findComponentById(ResourceTable.Id_detail_invoice_arrow);
        
        if (invoiceStatusText != null) {
            Integer invoiceStatus = orderData.getInvoiceStatus();
            if (invoiceStatus != null && invoiceStatus == 2) {
                // 已开发票
                invoiceStatusText.setText("已开发票");
                invoiceStatusText.setTextColor(new Color(0xFF333333));
                if (invoiceArrow != null) {
                    invoiceArrow.setVisibility(Component.HIDE);
                }
            } else {
                // 去开票
                invoiceStatusText.setText("去开票");
                invoiceStatusText.setTextColor(new Color(0xFFFF6600));
                if (invoiceArrow != null) {
                    invoiceArrow.setVisibility(Component.VISIBLE);
                }
                // TODO: 添加点击事件跳转到开票页面
            }
        }
    }

    /**
     * 设置文本内容的辅助方法
     */
    private void setText(int componentId, String text) {
        Text textComponent = (Text) rootLayout.findComponentById(componentId);
        if (textComponent != null) {
            textComponent.setText(text != null && !text.isEmpty() ? text : "--");
        }
    }

    /**
     * 设置组件可见性的辅助方法
     */
    private void setVisibility(int componentId, int visibility) {
        Component component = rootLayout.findComponentById(componentId);
        if (component != null) {
            component.setVisibility(visibility);
        }
    }
}

