package com.rehome.bhdxj.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.rehome.bhdxj.DBModel.Djjh;
import com.rehome.bhdxj.DBModel.DjjhList;
import com.rehome.bhdxj.R;
import com.rehome.bhdxj.activity.sbxdj.DjMainActivity;
import com.rehome.bhdxj.bean.XscbRequestBean;
import com.rehome.bhdxj.contans.Contans;
import com.rehome.bhdxj.utils.GsonUtils;
import com.rehome.bhdxj.utils.HttpListener;
import com.rehome.bhdxj.utils.NohttpUtils;
import com.rehome.bhdxj.utils.RSAUtils;
import com.rehome.bhdxj.utils.SPUtils;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.litepal.crud.DataSupport;

import java.util.List;

import static com.rehome.bhdxj.utils.GsonUtils.GsonToBean;


public class PushService extends IntentService {
    private int[] whats = new int[]{};
    public PushService() {
        super("PushService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setTheme(R.style.AppTheme);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            whats = intent.getExtras().getIntArray("what");
            requestData(whats);
        }
    }

    private void requestData(int[] what) {

        Request<String> qy = NoHttp.createStringRequest(Contans.IP + Contans.QY);
        NohttpUtils.getInstance().add(null, 12, qy, callback, false, false, "");
        for (int i = 0; i < what.length; i++) {
            switch (what[i]) {
                //点检
                case 1:
                    Request<String> requestdj = NoHttp.createStringRequest(Contans.IP + Contans.DJJHLIST, RequestMethod.POST);
                    requestdj.setDefineRequestBodyForJson(createZyJson());
                    NohttpUtils.getInstance().add(null, 1, requestdj, callback, false, false, "加载中...");
                    break;

            }
        }
    }


    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {

            switch (what) {

                case 1:
//                    Log.e("serviceData", response.get());
                    DjjhList list = GsonToBean(response.get(), DjjhList.class);
                    if (list != null) {
                        if (list.getState().equals("1")) {
                            int dbcount = -1;//数据库中是否有数据
                            List<Djjh> djjhs = list.getData();//服务器数据

                            //先删除未下 载的计划

                            DataSupport.deleteAll(Djjh.class, "download = 0");

                            for (Djjh djjh : djjhs) {

                                List<Djjh> dbdjjh = DataSupport.where("GWID = ? and download = ?", djjh.getGWID(), "1").find(Djjh.class);

                                //如果数据库中没有这条数据，就添加到数据库

                                if (dbdjjh.size() == 0) {

                                    dbcount = 1;

                                    djjh.save();
                                }
                            }
                            if (dbcount == 1) {

//                                shownotification(1, "您有新的点检计划");
                            }
                        } else {
                            DataSupport.deleteAll(Djjh.class, "download = 0");
                        }
                    }
                    break;

            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {

        }
    };

    private void shownotification(int what, String msg) {

        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingIntent;
        Intent intent = null;
        if (what == 0) {
//            intent = new Intent(this, XxzActivity.class);
        } else if (what == 1) {
//            intent = new Intent(this, SxcdjActivity.class);
            intent = new Intent(this, DjMainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else if (what == 2) {
//            intent = new Intent(this, AjhXzActivity.class);
        } else if (what == 3) {
//            intent = new Intent(this, AxwaqgcglActivity.class);
        }
        Notification notify;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        }

        notify = new Notification.Builder(this)
                .setTicker(System.currentTimeMillis() + "")
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setTicker("您有新的计划")
                .setContentTitle(msg)
                .setContentText("点击进入下载")
                .setContentIntent(pendingIntent).build(); // 需要注意build()是在API
        notify.defaults = Notification.DEFAULT_SOUND;
        // level16及之后增加的，API11可以使用getNotificatin()来替代
        notify.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时，通知将被清除。
        manager.notify(what, notify);
    }

    private String createZyJson() {
        String GWID = (String) SPUtils.get(getApplicationContext(), Contans.BZBH, "");

        String usernameTemp = (String) SPUtils.get(this, Contans.USERID,String.valueOf(""));

        String YHID = RSAUtils.decryptBASE64StrLocal(usernameTemp);
        XscbRequestBean info = new XscbRequestBean();
        info.setAction("DJ_GWLIST_GET");
        info.setGWID(GWID);
        info.setYHID(YHID);
        String json = GsonUtils.GsonString(info);
        return json;
    }


}