package com.example.register;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.example.register.entity.OrangeMessage;
import com.example.register.netrequest.OkHttpMessage;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class TimeService extends Service {
    private static Timer timer = null;
    private NotificationManager manager;
    private NotificationCompat.Builder builder;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 清除通知
     */
    private void cleanAllNotification() {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancelAll();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

    }

    /**
     * 添加通知
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        long period = 60 * 1000; //1分钟一个周期
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                new ConsumeMessageTask().execute();
            }
        }, 0, period);

        return super.onStartCommand(intent, flags, startId);
    }

    class ConsumeMessageTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            /**
             * NotificationChannel是android8.0新增的特性，如果App的targetSDKVersion>=26，
             * 没有设置channel通知渠道的话，就会导致通知无法展示。
             * 报错内容：Failed to post notification on channel “null”
             */
            OkHttpMessage okHttpMessage = new OkHttpMessage();
            OrangeMessage Message;
            try {
                Message = okHttpMessage.consumeMessage();
                if (!Objects.isNull(Message)) {
                    Log.i("orangeMessage", "run: " + Message.toString());
                    NotificationChannel channel = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                        channel = new NotificationChannel("channel", "通知", NotificationManager.IMPORTANCE_DEFAULT);
                    }
                    manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        manager.createNotificationChannel(channel);
                    }
                    builder = new NotificationCompat.Builder(TimeService.this);
                    Date date = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    builder.setContentTitle("来自美团的系统通知消息" + "  " + formatter.format(date));
                    builder.setSmallIcon(R.drawable.chengzi);
                    builder.setChannelId("channel");
                    builder.setContentText(Message.getContent());
                    builder.setAutoCancel(true);
                    builder.setDefaults(Notification.DEFAULT_ALL);
                    Notification notification = builder.build();
                    manager.notify(1, notification);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
