package com.tofly.ghrq_route.module.download.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

/*import com.android.volley.Request;
import com.android.volley.Response;*/
import com.android.volley.VolleyError;
import com.mgq.base.utils.space.SpaceUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.module.service.DownloadReceiver;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.common.ui.activity.DownloadMapActivity;
import com.tofly.ghrq_route.common.ui.dialog.DownloadListDialog;
import com.tofly.ghrq_route.common.util.net.volley.InputStreamVolleyRequest;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DownloadService extends Service {

    public static final int SUCCESS = 1;
    public static final int ERROR = 2;
    public static final int UNBIND = 3;
    public static final int PROGRESS = 4;

    private NotificationManager notificationManager;

    private Notification.Builder builder;

    private int result = 0;

    private DBDaoHelper dbDaoHelper;

    private String mDownFileName;
    private String mDownDataId;
    private int mDownPosition;


    @Override
    public IBinder onBind(Intent intent) {
        return new DownloadBinder();
    }


    public class DownloadBinder extends Binder {
        public Service getDownloadService() {
            return DownloadService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        dbDaoHelper = DBDaoHelper.getInstance();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mDownFileName = extras.getString(DownloadListDialog.FILENAME);
            mDownDataId = extras.getString(DownloadListDialog.ID);
            mDownPosition = extras.getInt(DownloadListDialog.POSITION);
            //downloadPipeByVolley(fileName,id,position);
            downloadPipe(mDownFileName, mDownDataId, mDownPosition);
        }

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

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case SUCCESS: {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString(DownloadListDialog.FILENAME, mDownFileName);
                    bundle.putString(DownloadListDialog.ID, mDownDataId);
                    bundle.putInt(DownloadListDialog.POSITION, mDownPosition);
                    int result = (int) msg.obj;
                    bundle.putInt("result", result);
                    intent.putExtras(bundle);
                    intent.setAction(DownloadReceiver.DownloadReceiverFinished);
                    sendBroadcast(intent);
                }
                break;
                case ERROR:
                    break;
                case UNBIND:
                    break;
                case PROGRESS: {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putInt("current", msg.arg1);
                    bundle.putInt("total", msg.arg2);
                    bundle.putInt("progress", (int) msg.obj);
                    bundle.putString(DownloadListDialog.FILENAME, mDownFileName);
                    bundle.putString(DownloadListDialog.ID, mDownDataId);
                    bundle.putInt(DownloadListDialog.POSITION, mDownPosition);
                    intent.setAction(DownloadReceiver.DownloadReceiverProgress);
                    intent.putExtras(bundle);
                    sendBroadcast(intent);
                }
                break;
            }

        }
    };

    public void downloadPipeByVolley(final String fileName, final String id, final int position) {
        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(id))
            return;

        final String token = BaseApp.getInstance().getLoginUser().getToken();
        String url = NetRequestURL.getDownloadMapUrl() + fileName;

        if (SpaceUtil.ExistSDCard()) {
            InputStreamVolleyRequest getRequest = new InputStreamVolleyRequest(com.android.volley.Request.Method.GET, url, new com.android.volley.Response.Listener<byte[]>() {
                @Override
                public void onResponse(byte[] response) {
                    // TODO handle the response
                    boolean mIsCancel = false;
                    String mgisDataPath = C.dir.data;
                    try {
                        showNotify("正在下载", position);
                        InputStream is = new ByteArrayInputStream(response);
                        int totallength = (int) response.length;
                        Log.w("TAG", "downloadPipe: totallength = " + totallength);
                        File apkFile = new File(mgisDataPath, fileName);
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        int currlength = 0;
                        byte[] buffer = new byte[1024];
                        int lastProgress = 0;
                        int mProgress;
                        while (!mIsCancel) {
                            int numread = is.read(buffer);
                            currlength += numread;
                            // 计算进度条的当前位置
                            mProgress = (int) (((float) currlength / totallength) *
                                    100);
                            if (mProgress > lastProgress) {
                                lastProgress = mProgress;
                                builder.setContentText("正在下载：" + mProgress + "%");
                                builder.setProgress(100, mProgress, false);
                                Notification build1 = builder.build();
                                notificationManager.notify(position, build1);
                            }
                            // 下载完成
                            if (numread < 0) {
                                mIsCancel = true;
                                builder.setContentText("下载完成");
                                builder.setProgress(0, 0, false);
                                Notification build1 = builder.build();
                                build1.flags = Notification.FLAG_AUTO_CANCEL;
                                notificationManager.notify(position, build1);
                                break;
                            }
                            fos.write(buffer, 0, numread);
                        }
                        if (mIsCancel) {
                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String format = df.format(new Date());
                        //    dbDaoHelper.updatePipeDb(id, format);
                            result = 1;
                        }
                        fos.close();
                        is.close();
                    } catch (IOException e) {
                        result = 2;
                        if (builder != null) {
                            builder.setContentText("下载失败");
                            builder.setProgress(0, 0, false);
                            Notification build1 = builder.build();
                            build1.flags = Notification.FLAG_AUTO_CANCEL;
                            notificationManager.notify(position, build1);
                        }
                    }
                    dbDaoHelper.updatePipeDbState(id, result);
                    handler.sendEmptyMessage(SUCCESS);
                }
            }, new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    result = 2;
                    dbDaoHelper.updatePipeDbState(id, result);
                    handler.sendEmptyMessage(SUCCESS);
                }
            }, null) {
                @Override
                public Map<String, String> getHeaders() {
                    //参数拼装:表单提交方式
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("token", token);
                    return params;
                }
            };
            BaseApp.addStreamRequest(this.getClass().getName(), getRequest);
        }
    }

    private void showNotify(String title, int position) {
        PendingIntent intent = PendingIntent.getActivity(DownloadService
                .this, 0x1, new Intent(DownloadService.this,
                DownloadMapActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
        Notification.Builder builder = new Notification.Builder(DownloadService.this)
                .setSmallIcon(R.mipmap.tofly_logo)
                .setContentTitle(title)
                .setWhen(System.currentTimeMillis())
                .setContentText("正在下载")
                .setOngoing(true)
                .setProgress(100, 0, false)
                .setContentIntent(intent);
        Notification build = builder.build();
        build.flags = Notification.FLAG_NO_CLEAR;
        notificationManager.notify(position, build);
    }

    public void downloadPipe(final String fileName, final String id, final int position) {
        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(id))
            return;
        new Thread((Runnable) () -> {
            DBDaoHelper dbDaoHelper = DBDaoHelper.getInstance();
            String token = BaseApp.getInstance().getLoginUser().getToken();

            String url = NetRequestURL.getDownloadMapUrl() + "?remotePath=/dyrq/mobile/" + fileName + "&fileName=" + fileName;
            if (SpaceUtil.ExistSDCard()) {
                int result = 0;
                String mgisDataPath = C.dir.data;

                OkHttpClient client = new OkHttpClient.Builder().
                        readTimeout(10, TimeUnit.SECONDS).
                        writeTimeout(10, TimeUnit.SECONDS).
                        connectTimeout(10, TimeUnit.SECONDS).
                        build();

                final Request request = new Request.Builder()
                        .url(url)
                        .addHeader("Authorization", "bearer " + token)
                        .get()
                        .build();
                Response response = null;
                boolean mIsCancel = false;
                Notification.Builder builder = null;
                NotificationManager nm = (NotificationManager) getSystemService
                        (NOTIFICATION_SERVICE);
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        PendingIntent intent = PendingIntent.getActivity(DownloadService
                                .this, 0x1, new Intent(DownloadService.this,
                                DownloadMapActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
                        builder = new Notification.Builder(DownloadService.this)
                                .setSmallIcon(R.mipmap.tofly_logo)
                                .setContentTitle(fileName)
                                .setWhen(System.currentTimeMillis())
                                .setContentText("正在下载")
                                .setOngoing(true)
                                .setProgress(100, 0, false)
                                .setContentIntent(intent);
                        Notification build = builder.build();
                        build.flags = Notification.FLAG_NO_CLEAR;
                        nm.notify(position, build);
                        ResponseBody body = response.body();
                        InputStream is = body.byteStream();
                        long totallength = (long) body.contentLength();
                        Log.w("TAG", "downloadPipe: totallength = " + totallength);
                        File apkFile = new File(mgisDataPath, fileName);

                        FileOutputStream fos = new FileOutputStream(apkFile);
                        long currlength = 0;
                        byte[] buffer = new byte[1024];
                        int lastProgress = 0;
                        int mProgress;
                        while (!mIsCancel) {
                            int numread = is.read(buffer);
                            currlength += numread;

                            // 计算进度条的当前位置
                            mProgress = (int) (((float) currlength / totallength) *
                                    100);
                            if (mProgress > lastProgress) {
                                lastProgress = mProgress;
                                builder.setContentText("正在下载：" + mProgress + "%");
                                builder.setProgress(100, mProgress, false);
                                Notification build1 = builder.build();
                                nm.notify(position, build1);
                                handler.sendMessage(handler.obtainMessage(PROGRESS, (int) (currlength / 1024), (int) (totallength / 1024), mProgress));
                            }
                            // 下载完成
                            if (numread < 0) {
                                mIsCancel = true;
                                builder.setContentText("下载完成");
                                builder.setProgress(0, 0, false);
                                Notification build1 = builder.build();
                                build1.flags = Notification.FLAG_AUTO_CANCEL;
                                nm.notify(position, build1);
//                                handler.post(progressRunnable);

                                break;
                            }
                            fos.write(buffer, 0, numread);
                        }
                        if (mIsCancel) {
                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String format = df.format(new Date());
                            dbDaoHelper.updatePipeDb(id,format);
                            result = 1;
                            builder.setContentText("下载完成");
                            builder.setProgress(0, 0, false);
                            Notification build1 = builder.build();
                            build1.flags = Notification.FLAG_AUTO_CANCEL;
                            nm.notify(position, build1);
                        }
                        fos.close();
                        is.close();
                    } else {
                        result = 2;

                    }
                    response.close();

                } catch (IOException e) {
                    result = 2;
                    if (builder != null) {
                        builder.setContentText("下载失败");
                        builder.setProgress(0, 0, false);
                        Notification build1 = builder.build();
                        build1.flags = Notification.FLAG_AUTO_CANCEL;
                        nm.notify(position, build1);
                    }
                }
                dbDaoHelper.updatePipeDbState(id, result);
                handler.sendMessage(handler.obtainMessage(SUCCESS, result));
            }
            // TODO: 2017/6/21 发送广播，通知 activity 刷新列表
        }).start();
    }
}
