package com.base.utils.tools.android;

import android.app.AlarmManager;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.text.format.DateFormat;

import com.base.utils.R;
import com.base.utils.tools.java.DateUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


/**
 * 调整Android系统时间
 */

public class SettingTimeUtil {

    private final static String GMT8 = "GMT+08:00";
    private static String TIME_ZONE_NOT_GMT8 = "";
    private static String DATE_TIME_NOT_AUTO = "";

    public interface OnAdjustLocalTimeListener {
        void done(boolean isSuccess, String timeZoneString, String dateTimeString);

        void onGetInternetTimeException(Exception e);
    }

    /**
     * 调整系统时间
     * */
    public static void adjustLocalTime(final Context mContext, final OnAdjustLocalTimeListener listener) {
        if (!is24HourFormat(mContext)) {
            //如果不是24小时制，则设置为24小时制
            set24HourFormat(mContext);
        }
        String gmt = getCurrentTimeZone();
        if (!gmt.equals(GMT8)) {
            //如果时区不是中国东8区，则设置为东八区时间
            TIME_ZONE_NOT_GMT8 = mContext.getString(R.string.resource_prompt_dialog_system_setting_time_zone_not_gmt8);
        } else {
            TIME_ZONE_NOT_GMT8 = "";
        }

        if (!isDateTimeAuto(mContext)) {
            //如果不是自动获取网络的时间，则设置为自动获取
            DATE_TIME_NOT_AUTO = mContext.getString(R.string.resource_prompt_dialog_system_setting_date_time_not_auto);
        } else {
            DATE_TIME_NOT_AUTO = "";
        }
        DateUtil.getBaiduTime(new DateUtil.OnInternetTimeListener() {
            @Override
            public void done(Date date, Exception e) {
                if (e == null) {
                    //获取时间成功
                    Date localData = new Date(System.currentTimeMillis());
                    //相差60秒以内为正常
                    long value = Math.abs(date.getTime() - localData.getTime());  //返回的是毫秒
                    if (value < 2000 * 60) {
                        //时间小于60秒说明正常
                        listener.done(true, null, null);
                    } else {
                        //说明时间相差10秒或以上，应该纠正  以下两个方法会报错//setSysDate(mContext,date.getYear(),date.getMonth(),date.getDay());//setSysTime(mContext,date.getHours(),date.getMinutes(),date.getSeconds());
                        listener.done(false, TIME_ZONE_NOT_GMT8, DATE_TIME_NOT_AUTO);
                    }
                } else {
                    //获取时间失败
                    DateUtil.getTaobaoTime(new DateUtil.OnInternetTimeListener() {
                        @Override
                        public void done(Date date, Exception e) {
                            if (e==null){
                                //获取时间成功
                                Date localData = new Date(System.currentTimeMillis());
                                //相差60秒以内为正常
                                long value = Math.abs(date.getTime() - localData.getTime());  //返回的是毫秒
                                if (value < 1000 * 60) {
                                    //时间小于60秒说明正常
                                    listener.done(true, null, null);
                                } else {
                                    //说明时间相差10秒或以上，应该纠正  以下两个方法会报错
                                    listener.done(false, TIME_ZONE_NOT_GMT8, DATE_TIME_NOT_AUTO);
                                }
                            }else {
                                listener.onGetInternetTimeException(e);
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * 系统时间是否是24小时的格式
     */
    public static boolean is24HourFormat(Context mContext) {
        return DateFormat.is24HourFormat(mContext);
    }

    public static void set24HourFormat(Context mContext) {
        //设置 24小时制
        android.provider.Settings.System.putString(mContext.getContentResolver(),
                android.provider.Settings.System.TIME_12_24, "24");

    }

    public static void set12HourFormat(Context mContext) {
        //设置 12小时制
        android.provider.Settings.System.putString(mContext.getContentResolver(),
                android.provider.Settings.System.TIME_12_24, "12");
    }


    //判断系统的时区是否是自动获取的

    public static boolean isTimeZoneAuto(Context mContext) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                return Settings.Global.getInt(mContext.getContentResolver(),
                        Settings.Global.AUTO_TIME_ZONE) > 0;
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        return false;
    }


    //设置系统的时区为中国标准时间
    public static void setGMT8Zone(Context mContext) {
        AlarmManager mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        mAlarmManager.setTimeZone(GMT8);
    }

    //判断系统的时间是否自动获取的
    public static boolean isDateTimeAuto(Context mContext) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                return Settings.Global.getInt(mContext.getContentResolver(),
                        Settings.Global.AUTO_TIME) > 0;
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    //设置系统时区

    public static void setTimeZone(String timeZone) {
        final Calendar now = Calendar.getInstance();
        TimeZone tz = TimeZone.getTimeZone(timeZone);
        now.setTimeZone(tz);
    }
    //获取系统当前的时区

    public static String getDefaultTimeZone() {
        return TimeZone.getDefault().getDisplayName();
    }

    //获取系统当前的时区
    public static String getCurrentTimeZone() {
        TimeZone tz = TimeZone.getDefault();
        return createGmtOffsetString(true, true, tz.getRawOffset());
    }

    public static String createGmtOffsetString(boolean includeGmt,
                                               boolean includeMinuteSeparator, int offsetMillis) {
        int offsetMinutes = offsetMillis / 60000;
        char sign = '+';
        if (offsetMinutes < 0) {
            sign = '-';
            offsetMinutes = -offsetMinutes;
        }
        StringBuilder builder = new StringBuilder(9);
        if (includeGmt) {
            builder.append("GMT");
        }
        builder.append(sign);
        appendNumber(builder, 2, offsetMinutes / 60);
        if (includeMinuteSeparator) {
            builder.append(':');
        }
        appendNumber(builder, 2, offsetMinutes % 60);
        return builder.toString();
    }

    private static void appendNumber(StringBuilder builder, int count, int value) {
        String string = Integer.toString(value);
        for (int i = 0; i < count - string.length(); i++) {
            builder.append('0');
        }
        builder.append(string);
    }
}
