package com.example.administrator.zhapp.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.DBModel.Ajhjh;
import com.example.administrator.zhapp.DBModel.AjhjhList;
import com.example.administrator.zhapp.DBModel.Djjh;
import com.example.administrator.zhapp.DBModel.DjjhList;
import com.example.administrator.zhapp.DBModel.Qy;
import com.example.administrator.zhapp.DBModel.QyList;
import com.example.administrator.zhapp.DBModel.XfDjjh;
import com.example.administrator.zhapp.DBModel.XfDjjhList;
import com.example.administrator.zhapp.DBModel.XwaqgcJh;
import com.example.administrator.zhapp.DBModel.XwaqgcJhList;
import com.example.administrator.zhapp.DBModel.Zy;
import com.example.administrator.zhapp.DBModel.ZyInfo;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.ajhxcgl.AjhXzActivity;
import com.example.administrator.zhapp.activity.ajhxcgl.AxwaqgcglActivity;
import com.example.administrator.zhapp.activity.sbxdjgl.SxcdjActivity;
import com.example.administrator.zhapp.activity.xfbwxcgl.XxzActivity;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.IpInfo;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.NohttpUtils;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.download.DownloadRequest;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.example.administrator.zhapp.utils.GsonUtils.GsonToBean;

public class PushService extends IntentService {

    private int[] whats = new int[]{};


    private String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/com.rehome.ydapp/";
    private String FILENAME = "rehome.apk";

    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) {

        File file = new File(PATH + FILENAME);
        //如果APK存在，就删除
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            }
        }

        Request<String> qy = NoHttp.createStringRequest(Contans.IP + Contans.QY);
        NohttpUtils.getInstance().addNoProgress(this, 12, qy, callback);

        Request<String> ck_ip = NoHttp.createStringRequest(Contans.IP + Contans.GET_CK_IP);
        NohttpUtils.getInstance().addNoProgress(this, 14, ck_ip, callback);


        for (int i = 0; i < what.length; i++) {
            switch (what[i]) {
                //消防保卫
                case 0:
                    Request<String> xfbw = NoHttp.createStringRequest(Contans.IP + Contans.XFDJJHALL);
                    String str = (String) SPUtils.get(getApplicationContext(), Contans.BZBH, "152145221");
                    xfbw.add("bzbh", UiUtlis.encoder(str));
                    NohttpUtils.getInstance().addNoProgress(this, 0, xfbw, callback);
                    break;
                //点检
                case 1:
                    showLog("点检");
                    Request<String> dj = NoHttp.createStringRequest(Contans.IP + Contans.DJJHLIST);
                    dj.add("BZMC", UiUtlis.encoder((String) SPUtils.get(getApplicationContext(), Contans.BZBH, "12108080101")));
                    NohttpUtils.getInstance().addNoProgress(this, 1, dj, callback);

                    Request<String> zy = NoHttp.createStringRequest(Contans.IP + Contans.QXGDZY);
                    NohttpUtils.getInstance().addNoProgress(this, 11, zy, callback);
                    break;
                //安建环
                case 2:
                    Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.AJHJHLIST);
                    request.add("BZMC", UiUtlis.encoder((String) SPUtils.get(getApplicationContext(), Contans.BZBH, "12108030201")));
                    NohttpUtils.getInstance().addNoProgress(this, 2, request, callback);
                    break;
                //行为安全观察
                case 3:
                    Request<String> xwaq = NoHttp.createStringRequest(Contans.IP + Contans.XWAQGC);
                    xwaq.add("gh", (String) SPUtils.get(getApplicationContext(), Contans.USERNAME, "310194"));
                    NohttpUtils.getInstance().addNoProgress(this, 3, xwaq, callback);
                    break;
            }
        }
    }

    private void downLoadAPK(String url) {
        DownloadRequest downloadRequest = NoHttp.createDownloadRequest(url, PATH, FILENAME, true, true);
        NohttpUtils.getDownloadInstance().add(0, downloadRequest, downloadListener);
    }

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


            switch (what) {
                //消防保卫
                case 0:
                    Log.e("serviceData",response.get());
                    XfDjjhList xfdjjh = GsonToBean(response.get(), XfDjjhList.class);
                    if (xfdjjh != null) {
                        if (Integer.parseInt(xfdjjh.getTotal()) != 0) {
                            //保存计划列表到数据库
                            int dbcount = -1;//数据库中是否有数据
                            List<XfDjjh> djjhs = xfdjjh.getRows();

                            DataSupport.deleteAll(XfDjjh.class, "download = 0");
                            for (XfDjjh djjh : djjhs) {
                                List<XfDjjh> dbdjjh = DataSupport.where("jhid = ? and download = ?", djjh.getJhid(), "1").find(XfDjjh.class);
                                if (dbdjjh.size() == 0) {
                                    dbcount = 1;
                                    djjh.save();
                                }
                            }

                            if (dbcount == 1) {
                                shownotification(0, "您有新的消防保卫计划");
                            }
                        } else {
                            DataSupport.deleteAll(XfDjjh.class, "download = 0");
                        }
                    }
                    break;
                case 1:
                    showLog("1");
                    showLog("点检");
                    showLog(response.get());
                    DjjhList list = GsonToBean(response.get(), DjjhList.class);
                    if (list != null) {
                        if (list.getTotal() != 0) {
                            int dbcount = -1;//数据库中是否有数据
                            List<Djjh> djjhs = list.getRows();//服务器数据

                            //先删除未下 载的计划
                            DataSupport.deleteAll(Djjh.class, "download = 0");

                            for (Djjh djjh : djjhs) {
                                List<Djjh> dbdjjh = DataSupport.where("jhid = ? and download = ?", djjh.getJHID(), "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;
                case 2:
                    Log.e("serviceData",response.get());
                    //安建环计划
                    AjhjhList info = GsonToBean(response.get(), AjhjhList.class);
                    if (info != null) {
                        if (info.getTotal() != 0) {
                            int dbcount = -1;//数据库中是否有数据
                            List<Ajhjh> djjhs = info.getRows();


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

                            for (Ajhjh ajhjh : djjhs) {
                                List<Ajhjh> ajhjhs = DataSupport.where("jhid = ? and download = ?", ajhjh.getJHID(), "1").find(Ajhjh.class);
                                if (ajhjhs.size() == 0) {
                                    dbcount = 1;
                                    ajhjh.save();
                                }
                            }

                            if (dbcount == 1) {
                                shownotification(2, "您有新的安健环计划");
                            }
                        } else {
                            DataSupport.deleteAll(Ajhjh.class, "download = 0");
                        }

                    }
                    break;
                case 3:
                    //行为安全观察
                    XwaqgcJhList xwaq = GsonToBean(response.get(), XwaqgcJhList.class);
                    if (xwaq != null) {
                        if (xwaq.getTotal() != 0) {
                            List<XwaqgcJh> jhs = new ArrayList<>();

                            jhs.addAll(xwaq.getRows());
                            DataSupport.deleteAll(XwaqgcJh.class);
                            int dbcount = -1;//数据库中是否有数据
                            for (XwaqgcJh jh : jhs) {
                                List<XwaqgcJh> dbdjjh = DataSupport.where("jhid=?", jh.getJHID()).find(XwaqgcJh.class);
                                //如果数据库中没有这要数据,就添加
                                if (dbdjjh.size() == 0) {
                                    dbcount = 1;
                                    jh.save();
                                }
                            }

                            if (dbcount == 1) {
                                shownotification(3, "您有新的行为安全观察计划");
                                Intent intent = new Intent();
                                intent.putExtra("isTask", true);
                                intent.setAction("com.example.administrator.zhapp.RECEIVER");
                                sendBroadcast(intent);
                            }
                        } else {
                            DataSupport.deleteAll(XwaqgcJh.class);
                            Intent intent = new Intent();
                            intent.putExtra("isTask", false);
                            intent.setAction("com.example.administrator.zhapp.RECEIVER");
                            sendBroadcast(intent);
                        }
                    }
                    break;
                //专业
                case 11:
                    ZyInfo zy = GsonToBean(response.get(), ZyInfo.class);
                    if (zy != null) {

                        if (zy.getRows().size() != 0) {
                            if (DataSupport.count("zy") != 0) {
                                int i = DataSupport.deleteAll(Zy.class);
                                if (i != 0) {
                                    DataSupport.saveAll(zy.getRows());
                                }
                            } else {
                                DataSupport.saveAll(zy.getRows());
                            }
                        }
                    }
                    break;
                case 12:
                    QyList qys = GsonToBean(response.get(), QyList.class);
                    if (qys != null) {

                        if (qys.getRows().size() != 0) {
                            if (Qy.count("qy") != 0) {
                                int i = DataSupport.deleteAll(Qy.class);
                                if (i != 0) {
                                    DataSupport.saveAll(qys.getRows());
                                }
                            } else {
                                DataSupport.saveAll(qys.getRows());
                            }
                        }
                    }
                    break;

                case 13:
//                    AppUploadInfo appUploadInfo = GsonToBean(response.get(), AppUploadInfo.class);
//                    if (appUploadInfo != null) {
//                        if (!appUploadInfo.getTotal().equals("0")) {
//                            AppUploadInfo.VersoinInfo versoinInfo = appUploadInfo.getRows().get(0);
//                            if (!versoinInfo.getVersionname().equals(getVersionName())) {
////                                downLoadAPK(versoinInfo.getApkurl());
//                            }
//                        }
//                    }
                    break;

                case 14:

//                    IpInfo ipInfo = GsonUtils.GsonToBean(response.get(), IpInfo.class);
//                    if (ipInfo != null) {
//                        if (!ipInfo.getTotal().equals("0")) {
//                            Contans.CK_BASE_IP = ipInfo.getRows().get(0).getModulename();
//                        }
//                    }

                    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);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else if (what == 1) {
            intent = new Intent(this, SxcdjActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else if (what == 2) {
            intent = new Intent(this, AjhXzActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else if (what == 3) {
            intent = new Intent(this, AxwaqgcglActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        }
        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, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        notify = new Notification.Builder(this)
                .setTicker(System.currentTimeMillis() + "")
                .setSmallIcon(R.mipmap.logo1)
                .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 com.yolanda.nohttp.download.DownloadListener downloadListener = new com.yolanda.nohttp.download.DownloadListener() {
        @Override
        public void onDownloadError(int what, Exception exception) {

        }

        @Override
        public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {

        }

        @Override
        public void onProgress(int what, int progress, long fileCount) {

        }

        @Override
        public void onFinish(int what, String filePath) {
            //下载完成
            AlertDialog.Builder builder = new AlertDialog.Builder(PushService.this);
            builder.setCancelable(false);
            builder.setTitle("发现新版本");
            builder.setMessage("单击更新升级到最新版本");
            builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //跳转到安装界面
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    //从serivce启动必须要使用这个
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    File apkFile = new File(PATH + FILENAME);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri contentUri = FileProvider.getUriForFile(PushService.this, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    }
//                    intent.setDataAndType(Uri.parse("file://" + PATH + FILENAME),
//                            "application/vnd.android.package-archive");// File.toString()会返回路径信息
                    startActivity(intent);
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
            dialog.show();
            //builder.show();
        }

        @Override
        public void onCancel(int what) {

        }
    };


    /**
     * 返回版本号
     *
     * @return 非0 则代表获取成功
     */
    private int getVersionCode() {
        //1,包管理者对象packageManager
        PackageManager pm = getPackageManager();
        //2,从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号),传0代表获取基本信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            //3,获取版本名称
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取版本名称:清单文件中
     *
     * @return 应用版本名称    返回null代表异常
     */
    private String getVersionName() {
        //1,包管理者对象packageManager
        PackageManager pm = getPackageManager();
        //2,从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号),传0代表获取基本信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            //3,获取版本名称
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public void showLog(String logText) {
        if (BuildConfig.LOG_ERROR) {
            if(TextUtils.isEmpty(logText)){
                Log.i("app", "logText is null");
            }else{
                Log.i("app", logText);
            }
        }
    }
}