package com.fujica.abk.utils;

import com.fujica.abk.ResourceTable;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Picker;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 日期选择对话框
 * 用于选择年月（格式：YYYY-MM）
 */
public class DateDialog extends CommonDialog {
    private Context context;
    private Picker yearPicker;
    private Picker monthPicker;
    private String selectedDate;
    private OnDateSelectedListener listener;

    // 回调接口
    public interface OnDateSelectedListener {
        void onDateSelected(String date);
    }

    /**
     * 构造函数
     */
    public DateDialog(Context context, String currentDate, OnDateSelectedListener listener) {
        super(context);
        this.context = context;
        this.selectedDate = currentDate;
        this.listener = listener;
        initDialog();
    }

    /**
     * 初始化对话框
     */
    private void initDialog() {
        setAutoClosable(true);
        setCornerRadius(ScreenUtil.vp2px(context, 10));
        setTransparent(true);
        // 加载XML布局
        DirectionalLayout mainLayout = (DirectionalLayout) LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_layout_date_dialog, null, false);
        
        // 获取组件引用
        yearPicker = (Picker) mainLayout.findComponentById(ResourceTable.Id_year_picker);
        monthPicker = (Picker) mainLayout.findComponentById(ResourceTable.Id_month_picker);
        Text btnConfirm = (Text) mainLayout.findComponentById(ResourceTable.Id_btn_confirm);
        mainLayout.findComponentById(ResourceTable.Id_close).setClickedListener(v->{
            destroy();
        });

        // 初始化数据
        initPickerData();

        // 设置确认按钮点击事件
        btnConfirm.setClickedListener(component -> {
            int yearIndex = yearPicker.getValue();
            int monthIndex = monthPicker.getValue();
            String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR) - 10 + yearIndex);
            String month = String.format("%02d", monthIndex + 1);
            String date = year + "-" + month;
            if (listener != null) {
                listener.onDateSelected(date);
            }
            destroy();
        });

        setContentCustomComponent(mainLayout);
    }

    /**
     * 初始化选择器数据
     */
    private void initPickerData() {
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH);

        // 初始化年份数据（当前年份前后各10年）
        List<String> yearList = new ArrayList<>();
        for (int i = currentYear - 10; i <= currentYear + 10; i++) {
            yearList.add(String.valueOf(i));
        }
        yearPicker.setDisplayedData(yearList.toArray(new String[0]));
        yearPicker.setMinValue(0);
        yearPicker.setMaxValue(yearList.size() - 1);
        yearPicker.setValue(10); // 默认选中当前年份

        // 初始化月份数据
        List<String> monthList = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            monthList.add(String.format("%02d月", i));
        }
        monthPicker.setDisplayedData(monthList.toArray(new String[0]));
        monthPicker.setMinValue(0);
        monthPicker.setMaxValue(11);
        monthPicker.setValue(currentMonth); // 默认选中当前月份

        // 如果传入了当前日期，设置选中值
        if (selectedDate != null && !selectedDate.isEmpty()) {
            try {
                String[] parts = selectedDate.split("-");
                if (parts.length == 2) {
                    int year = Integer.parseInt(parts[0]);
                    int month = Integer.parseInt(parts[1]);
                    
                    // 设置年份
                    int yearIndex = year - (currentYear - 10);
                    if (yearIndex >= 0 && yearIndex < yearList.size()) {
                        yearPicker.setValue(yearIndex);
                    }
                    
                    // 设置月份
                    if (month >= 1 && month <= 12) {
                        monthPicker.setValue(month - 1);
                    }
                }
            } catch (Exception e) {
                // 忽略解析错误，使用默认值
            }
        }
    }
}

