package ai.pai.lensman.service;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import ai.pai.lensman.BuildConfig;
import ai.pai.lensman.bean.OrderBean;
import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.db.Preferences;
import ai.pai.lensman.utils.BoxUrlContainer;
import ai.pai.lensman.utils.Constants;
import ai.pai.lensman.utils.HttpPostTask;
import ai.pai.lensman.utils.UrlContainer;

public class OrderDealService extends Service implements Handler.Callback{

    private ArrayList<OrderBean> orderList;
    private Handler handler;
    private OrderServiceListener listener;

    private static final int MSG_QUERY_ORDER = 2001;

    private static final String TAG = "OrderDealService";

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler(this);
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isQueueEmpty()) {
            return START_STICKY;
        }
        startQuery();
        return START_STICKY;
    }

    private void startQuery() {
        HashMap<String, String> params = new HashMap<>();
        params.put("user_id", Preferences.getInstance().getLensManId());
        new HttpPostTask(params) {

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d(TAG, "startQuery 查询是否有新订单 = " + response);
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        JSONObject data = json.getJSONObject("data");
                        JSONArray orders = data.getJSONArray("wanted");
                        if (orders != null && orders.length() > 0) {
                            orderList = new ArrayList<OrderBean>();
                            for (int k = 0; k < orders.length(); k++) {
                                JSONObject orderObj = orders.getJSONObject(k);
                                OrderBean bean = new OrderBean();
                                bean.sessionId = orderObj.getString("session_id");
                                bean.photoId = orderObj.getString("photo_id");
                                bean.orderId = orderObj.getString("order_id");
                                JSONObject photoObj = orderObj.getJSONObject("group_photo_info");
                                bean.buyerId = photoObj.getString("user_id");
                                bean.buyerName = photoObj.getString("nickname");
                                bean.originExpireTime = photoObj.getLong("origin_expired_stamps");
                                orderList.add(bean);
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                if(listener!= null) {
                    if (orderList != null && orderList.size() > 0) {
                        listener.onOrderArrived();
                        LogHelper.d(TAG,"有新的订单");
                    }else{
                        listener.onOrderCompleted();
                        LogHelper.d(TAG,"当前没有新订单");
                    }
                }
                dealOrder();
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                LogHelper.d(TAG,"查询新订单失败");
                dealOrder();
            }
        }.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.QUERY_ORIGIN_ORDER_URL);

    }

    private void dealOrder() {
        if (!isQueueEmpty()) {
            OrderBean orderBean = orderList.get(0);
            LogHelper.d(TAG,"当前有未处理的订单" +orderBean);
            fetchOriginFromBox(orderBean);
        } else {
            LogHelper.d(TAG,"当前没有订单，10s后再次查询");
            handler.removeMessages(MSG_QUERY_ORDER);
            handler.sendEmptyMessageDelayed(MSG_QUERY_ORDER,10000);
        }
    }

    private void fetchOriginFromBox(final OrderBean orderBean) {
        LogHelper.d(TAG, "fetchOriginFromBox 从box中获取原图 "+orderBean);
        HashMap<String, String> params = new HashMap<>();
        params.put("lensman", Preferences.getInstance().getLensManId());
        params.put("session", orderBean.sessionId);
        params.put("id", orderBean.photoId);

        //TODO for test
        if(BuildConfig.isTestMode){
            PhotoBean bean = new PhotoBean();
            bean.photoId = Long.parseLong(orderBean.photoId);
            bean.photoName = bean.photoId+".jpg";
            bean.photoPath = "http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1402/12/c1/31189058_1392186616852.jpg";
            bean.captureTime = bean.photoId;
            bean.isRawPhoto = false;
            bean.uploadStatus =  PhotoBean.UploadStatus.STATUS_NO_BEGIN;
            bean.sessionId = orderBean.sessionId;
            bean.lensmanId = Preferences.getInstance().getLensManId();
            orderBean.photoBean = bean;
            new SavePhotoTask(orderBean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), orderBean);
            return;
        }
        new HttpPostTask(params) {

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d(TAG, "fetchOriginFromBox get response string = " + response);
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        JSONObject data = json.getJSONObject("data");
                        PhotoBean bean = new PhotoBean();
                        bean.photoId = Long.parseLong(orderBean.photoId);
                        bean.photoName = bean.photoId+".jpg";
                        bean.photoPath = data.getString("path");
                        bean.captureTime = bean.photoId;
                        bean.isRawPhoto = false;
                        bean.uploadStatus =  PhotoBean.UploadStatus.STATUS_NO_BEGIN;
                        bean.sessionId = orderBean.sessionId;
                        bean.lensmanId = Preferences.getInstance().getLensManId();
                        orderBean.photoBean = bean;
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                LogHelper.d(TAG,"fetchOriginFromBox onPostFail 获取原图失败");
                orderList.remove(orderBean);
                dealOrder();
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                if(TextUtils.isEmpty(orderBean.photoBean.photoPath)){
                    LogHelper.d(TAG,"fetchOriginFromBox onPostSuccess 获取原图失败，因为原图已被删除");
                    reportOriginPhotoDeleted(orderBean);
                }else{
                    LogHelper.d(TAG,"fetchOriginFromBox onPostSuccess 获取原图地址成功，准备保存");
                    new SavePhotoTask(orderBean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), orderBean);
                }
            }
        }.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.FETCH_ORIGIN_URL);

    }

    private void uploadOrigin(OrderBean bean) {
        new UploadTask(bean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor());
    }

    private boolean isQueueEmpty() {
        return (orderList == null || orderList.size() == 0);
    }

    @Override
    public boolean handleMessage(Message message) {

        if(message.what == MSG_QUERY_ORDER){
            startQuery();
        }
        return true;
    }

    public class OrderServiceBinder extends Binder {

        public OrderDealService getService() {
            return OrderDealService.this;
        }

    }

    class SavePhotoTask extends AsyncTask<OrderBean, Integer, Boolean> {

        private OrderBean orderBean;

        public SavePhotoTask(OrderBean bean) {
            this.orderBean = bean;
        }

        @Override
        protected Boolean doInBackground(OrderBean... params) {

            String path = BoxUrlContainer.PHOTO_PATH_PREFIX_URL + orderBean.photoBean.photoPath;
            if(BuildConfig.isTestMode){
                path = "http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1402/12/c1/31189058_1392186616852.jpg";
            }
            LogHelper.d(TAG, "SavePhotoTask 保存照片到本地，图片链接地址为" + path);
            FileOutputStream fOut = null;
            HttpURLConnection conn = null;
            InputStream inStream = null;
            try {
                URL url = new URL(path);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                inStream = conn.getInputStream();
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    String dirPath = ai.pai.lensman.utils.Constants.APP_IMAGE_DIR + File.separator + orderBean.photoBean.sessionId + File.separator + Constants.ORIGIN_DIR_NAME;
                    File dir = new File(dirPath);
                    dir.mkdirs();
                    File file = new File(dir, orderBean.photoBean.photoName);
                    fOut = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = inStream.read(buffer)) != -1) {
                        fOut.write(buffer, 0, len);
                        fOut.flush();
                    }
                    fOut.flush();
                    LogHelper.d(TAG, "SavePhotoTask 保存照片到本地，图片保存至" + file.getAbsolutePath() + "图片大小为" + file.length() + "字节\n\n");
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    inStream.close();
                    conn.disconnect();
                    fOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                LogHelper.d(TAG,"savePhotoTask onPostExecute success 保存本地成功，准备上传");
                uploadOrigin(orderBean);
            } else {
                LogHelper.d(TAG,"savePhotoTask onPostExecute fail 保存本地失败，下次重试");
                orderList.remove(orderBean);
                dealOrder();
            }
        }
    }
    private void reportOriginPhotoDeleted(final OrderBean orderBean) {
        HashMap<String, String> params = new HashMap<>();
        params.put("user_id", Preferences.getInstance().getLensManId());
        params.put("session_id", orderBean.sessionId);
        params.put("order_id", orderBean.orderId);
        params.put("photo_id", orderBean.photoId);
        params.put("deleted", String.valueOf(1));
        new HttpPostTask(params) {

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d(TAG, "reportOriginPhotoDeleted get response string = " + response);
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                orderList.remove(orderBean);
                dealOrder();
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                orderList.remove(orderBean);
                dealOrder();
            }
        }.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.ORIGIN_PHOTO_UPLOAD_URL);

        LogHelper.d(TAG,"reportOriginPhotoDeleted task executes 上报服务器原图已删除");
    }
    public class UploadTask extends AsyncTask<Void, Integer, Boolean> {

        private OrderBean bean;

        public UploadTask(OrderBean bean) {
            this.bean = bean;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            for (int k = 0; k < 3; k++) {
                try {
                    String dirPath = ai.pai.lensman.utils.Constants.APP_IMAGE_DIR + File.separator + bean.sessionId
                            + File.separator + Constants.ORIGIN_DIR_NAME;
                    File dir = new File(dirPath);
                    dir.mkdirs();
                    File photo = new File(dir, bean.photoBean.photoName);
                    LogHelper.d(TAG, "上传照片 第" + k + "次尝试" + bean);
                    if (photo.exists() && photo.isFile()) {
                        PhotoUploadUtils photoUploadUtils = new PhotoUploadUtils(UrlContainer.ORIGIN_PHOTO_UPLOAD_URL + "?timestamp=" + System.currentTimeMillis());
                        photoUploadUtils.addTextParameter("deleted", String.valueOf(0));
                        photoUploadUtils.addFileParameter("photo", photo);
                        photoUploadUtils.addTextParameter("user_id", bean.photoBean.lensmanId);
                        photoUploadUtils.addTextParameter("order_id", bean.orderId);
                        photoUploadUtils.addTextParameter("session_id", bean.photoBean.sessionId);
                        photoUploadUtils.addTextParameter("photo_id", String.valueOf(bean.photoBean.photoId));

                        String result = new String(photoUploadUtils.send(false), "UTF-8");
                        JSONObject resultObj = new JSONObject(result);
                        if (resultObj.getInt("status") == 200) {
                            LogHelper.d(TAG, "上传 UploadTask upload result ok ");
                            return true;
                        }
                    } else {
                        return false;
                    }

                } catch (Exception e) {
                    LogHelper.d(TAG, "上传发生异常 UploadTask :" + bean + " error:" + e);
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            LogHelper.d(TAG, "上传 UploadTask " + bean + "  success ");
            orderList.remove(bean);
            dealOrder();
        }
    }

    public void setOrderServiceListener(OrderServiceListener listener){
        this.listener = listener;
    }

    public interface OrderServiceListener{
        void onOrderArrived();
        void onOrderCompleted();
    }

}
