 * 自定义日期时间选择器控件，支持12/24小时制切换
 */
public class DateTimePicker extends FrameLayout {
    // 默认启用状态
    private static final boolean DEFAULT_ENABLE_STATE = true;

    // 时间格式常量
    private static final int HOURS_IN_HALF_DAY = 12;         // 半日小时数（AM/PM制）
    private static final int HOURS_IN_ALL_DAY = 24;           // 全日小时数（24小时制）
    private static final int DAYS_IN_ALL_WEEK = 7;           // 日期选择范围（一周）
    private static final int DATE_SPINNER_MIN_VAL = 0;       // 日期选择器最小值
    private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值
    private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;   // 24小时制小时最小值
    private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;  // 24小时制小时最大值
    private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;   // 12小时制小时最小值
    private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;  // 12小时制小时最大值
    private static final int MINUT_SPINNER_MIN_VAL = 0;       // 分钟最小值
    private static final int MINUT_SPINNER_MAX_VAL = 59;      // 分钟最大值
    private static final int AMPM_SPINNER_MIN_VAL = 0;        // AM/PM最小值
    private static final int AMPM_SPINNER_MAX_VAL = 1;         // AM/PM最大值

    // UI控件
    private final NumberPicker mDateSpinner;    // 日期选择器
    private final NumberPicker mHourSpinner;    // 小时选择器
    private final NumberPicker mMinuteSpinner;  // 分钟选择器
    private final NumberPicker mAmPmSpinner;     // AM/PM选择器

    // 数据存储
    private Calendar mDate;                    // 当前选择的日期时间
    private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 日期显示文本缓存
    private boolean mIsAm;                     // 是否为上午
    private boolean mIs24HourView;              // 是否24小时制
    private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件启用状态
    private boolean mInitialising;              // 初始化标志位

    // 监听器接口
    public interface OnDateTimeChangedListener {
        void onDateTimeChanged(DateTimePicker view, int year, int month, 
                int dayOfMonth, int hourOfDay, int minute);
    }
    private OnDateTimeChangedListener mOnDateTimeChangedListener;

    // 日期变更监听器
    private NumberPicker.OnValueChangeListener mOnDateChangedListener = 
        new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            // 计算日期差值并更新Calendar对象
            mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
            updateDateControl();  // 刷新日期显示
            onDateTimeChanged();  // 触发回调
        }
    };

    // 小时变更监听器（处理跨日逻辑）
    private NumberPicker.OnValueChangeListener mOnHourChangedListener = 
        new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            boolean isDateChanged = false;
            Calendar cal = Calendar.getInstance();
            
            // 12小时制特殊处理
            if (!mIs24HourView) {
                // 处理AM/PM自动切换
                if ((!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) ||
                    (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1)) {
                    mIsAm = !mIsAm;
                    updateAmPmControl();
                }
                // 处理跨日情况
                if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY && !mIsAm) {
                    cal.setTimeInMillis(mDate.getTimeInMillis());
                    cal.add(Calendar.DAY_OF_YEAR, 1);
                    isDateChanged = true;
                } else if (oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1 && mIsAm) {
                    cal.setTimeInMillis(mDate.getTimeInMillis());
                    cal.add(Calendar.DAY_OF_YEAR, -1);
                    isDateChanged = true;
                }
            } else {
                // 24小时制跨日处理
                if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
                    cal.add(Calendar.DAY_OF_YEAR, 1);
                    isDateChanged = true;
                } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
                    cal.add(Calendar.DAY_OF_YEAR, -1);
                    isDateChanged = true;
                }
            }
            
            // 更新小时数值
            int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
            mDate.set(Calendar.HOUR_OF_DAY, newHour);
            
            // 处理日期变更
            if (isDateChanged) {
                setCurrentYear(cal.get(Calendar.YEAR));
                setCurrentMonth(cal.get(Calendar.MONTH));
                setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
            }
            onDateTimeChanged();
        }
    };

    // 分钟变更监听器（处理小时进位）
    private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = 
        new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            int min = mMinuteSpinner.getMinValue();
            int max = mMinuteSpinner.getMaxValue();
            int offset = 0;
            
            // 处理分钟循环滚动
            if (oldVal == max && newVal == min) {  // 59->00
                offset += 1;  // 增加1小时
            } else if (oldVal == min && newVal == max) {  // 00->59
                offset -= 1;  // 减少1小时
            }
            
            // 更新小时
            if (offset != 0) {
                mDate.add(Calendar.HOUR_OF_DAY, offset);
                mHourSpinner.setValue(getCurrentHour());
                updateDateControl();
                
                // 自动切换AM/PM显示
                int newHour = getCurrentHourOfDay();
                mIsAm = (newHour < HOURS_IN_HALF_DAY);
                updateAmPmControl();
            }
            
            // 设置分钟值
            mDate.set(Calendar.MINUTE, newVal);
            onDateTimeChanged();
        }
    };

    // AM/PM切换监听器
    private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = 
        new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            mIsAm = !mIsAm;
            // 调整小时数值
            if (mIsAm) {
                mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
            } else {
                mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
            }
            updateAmPmControl();
            onDateTimeChanged();
        }
    };

    // 构造函数组
    public DateTimePicker(Context context) {
        this(context, System.currentTimeMillis());
    }

    public DateTimePicker(Context context, long date) {
        this(context, date, DateFormat.is24HourFormat(context));
    }

    // 主构造函数
    public DateTimePicker(Context context, long date, boolean is24HourView) {
        super(context);
        // 初始化时间对象
        mDate = Calendar.getInstance();
        mInitialising = true;  // 设置初始化标志
        
        // 加载布局
        inflate(context, R.layout.datetime_picker, this);
        
        // 初始化日期选择器
        mDateSpinner = (NumberPicker) findViewById(R.id.date);
        mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
        mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
        mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
        
        // 初始化小时选择器
        mHourSpinner = (NumberPicker) findViewById(R.id.hour);
        mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
        
        // 初始化分钟选择器
        mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
        mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
        mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
        mMinuteSpinner.setOnLongPressUpdateInterval(100); // 长按加速间隔
        mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
        
        // 初始化AM/PM选择器
        String[] ampmStrings = new DateFormatSymbols().getAmPmStrings();
        mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
        mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
        mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
        mAmPmSpinner.setDisplayedValues(ampmStrings);  // 设置AM/PM本地化文本
        mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
        
        // 初始化显示状态
        updateDateControl();    // 更新日期显示
        updateHourControl();    // 更新小时显示
        updateAmPmControl();    // 更新AM/PM显示
        set24HourView(is24HourView); // 设置时间格式
        setCurrentDate(date);   // 设置初始时间
        
        // 设置控件启用状态
        setEnabled(mIsEnabled);
        mInitialising = false;  // 结束初始化
    }

    // 启用/禁用控件
    @Override
    public void setEnabled(boolean enabled) {
        if (mIsEnabled == enabled) return;
        super.setEnabled(enabled);
        // 级联设置子控件状态
        mDateSpinner.setEnabled(enabled);
        mMinuteSpinner.setEnabled(enabled);
        mHourSpinner.setEnabled(enabled);
        mAmPmSpinner.setEnabled(enabled);
        mIsEnabled = enabled;
    }

    // 获取当前时间（毫秒）
    public long getCurrentDateInTimeMillis() {
        return mDate.getTimeInMillis();
    }

    // 设置当前时间（毫秒）
    public void setCurrentDate(long date) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date);
        setCurrentDate(
            cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH),
            cal.get(Calendar.DAY_OF_MONTH),
            cal.get(Calendar.HOUR_OF_DAY),
            cal.get(Calendar.MINUTE)
        );
    }
}


