package com.efounder.chat.http;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.frame.utils.Constants;
import com.efounder.utils.FileUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author long
 *         2016年7月28日20:36:34
 */
public class OKHttpUtils {

    private static final String TAG = "OKHttpUtils";

    private static OkHttpClient mOKHttpClient = new OkHttpClient();

    /**
     * @param urlPath
     * @param desFilePath
     */
    public static void downLoadFiles(final Context mContext, final int type, String urlPath,
                                     final String desFilePath, ProgressResponseListener progressResponseListener,
                                     final DownloadListener downloadListener) {
        Log.i(TAG, "---downLoadFiles---");
        Request request = new Request.Builder().url(urlPath).build();
        if (progressResponseListener != null) {
            ProgressHelper.addProgressResponseListener(mOKHttpClient, progressResponseListener)
                    .newCall(request).enqueue(new Callback() {
                @Override
                public void onResponse(Call arg0, Response response) throws IOException {
                    if (null != response) {
                        byteToFile(mContext, type, response.body().bytes(), desFilePath);
                        if (downloadListener != null)
                            downloadListener.onSuccess(desFilePath);
                    }
                }

                @Override
                public void onFailure(Call arg0, IOException arg1) {
                    if (downloadListener != null)
                        downloadListener.onFailure();
                }
            });
        } else {
            mOKHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onResponse(Call arg0, Response response) throws IOException {
                    if (null != response) {
                        byteToFile(mContext, type, response.body().bytes(), desFilePath);
                        if (downloadListener != null)
                            downloadListener.onSuccess(desFilePath);
                    }
                }

                @Override
                public void onFailure(Call arg0, IOException arg1) {
                    if (downloadListener != null)
                        downloadListener.onFailure();
                }
            });
        }
    }

    /**
     * byte[]数组转为file文件
     *
     * @param datas
     * @param desFilePath 目标文件存储路径
     */
    public static void byteToFile(Context mContext, int type, byte[] datas, String desFilePath) {
        File file = new File(desFilePath);
        InputStream is = new ByteArrayInputStream(datas);
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            long sum = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
            }
            fos.flush();
            Log.d(TAG, "文件生成成功");
            executeFileByType(type, desFilePath);
        } catch (Exception e) {
            Log.d(TAG, "文件生成失败");
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        }

    }

    private static void executeFileByType(int type, String desFilePath) {
        if (callBack != null) {
            switch (type) {
                case MessageChildTypeConstant.subtype_voice:
                    callBack.downLoadCallBack(desFilePath);
                    break;
                case MessageChildTypeConstant.subtype_smallVideo:
                    callBack.downLoadCallBack(desFilePath);
                    break;
                case MessageChildTypeConstant.subtype_file:
                    callBack.downLoadCallBack(desFilePath);
                default:
                    break;
            }
        }
    }

    public interface DownLoadCallBack {
        public void downLoadCallBack(String result);
    }

    public static DownLoadCallBack callBack;
    //此方法多余,弃用
//	public static void playRecord(Context mContext,TextView voiceLengthView,String voicePath){
//		// 设置录音时间
//				File file = new File(voicePath);
//				String length = "0";
//				if (file.exists()) {
//					MediaPlayer mPlayer = MediaPlayer.create(mContext,
//							Uri.parse(voicePath));
//					if(null!=mPlayer){
//						int len = mPlayer.getDuration() / 1000 == 0 ? 1 : mPlayer
//								.getDuration() / 1000 + 1;
//						length = Integer.toString(len);
//					}
//				}
//
//				voiceLengthView.setText(length + '"');
//	}

    /**
     * 生成临时存储地址 后期改为app缓存目录
     *
     * @param fileName temp
     * @param suffix   .mp4\.amr
     * @throws IOException
     */
    public static String createTempDir(String fileName, String suffix) throws IOException {
        File sampleDir = new File(Environment.getExternalStorageDirectory() + File.separator + "im/media/");
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        File vecordDir = sampleDir;
        // 创建文件
        File tempFile = File.createTempFile(fileName, suffix, vecordDir); //mp4格式
        return tempFile.getAbsolutePath();
    }

    public interface DownloadListener {

        public void onSuccess(String path);

        public void onFailure();

    }

    /**
     * 使用poro的方式上传图片
     *
     * @param imgPath
     */
    public static int uploadImgWithSVR(String imgPath, String params) {

        EFRowSet imageRowSet = new EFRowSet();
        EAI.Protocol = EnvironmentVariable.getProperty("Protocol", "http");//http
        EAI.Server = EnvironmentVariable.getProperty("Server", "11.11.48.20");//11.11.48.20
        EAI.Port = EnvironmentVariable.getProperty("Port", "8001");//8001
        EAI.Path = EnvironmentVariable.getProperty("Path", "OSPServer");//OSPServer
        EAI.Service = EnvironmentVariable.getProperty("Service", "Android");//Android
        try {
            JSONObject jsonObject = new JSONObject(params);
            Iterator iterator = jsonObject.keys();
            while (iterator.hasNext()) {
                String key = iterator.next() + "";
                imageRowSet.putObject(key, jsonObject.get(key));
            }
            //byte[] data = FileUtils.FileToByte(imgPath);
            imageRowSet.putObject("imgByte", FileUtils.FileToByte(imgPath));
            imageRowSet.putString("F_MC", imgPath.substring(imgPath.lastIndexOf("/") + 1, imgPath.length()));
            imageRowSet.putString("F_SOURCE", "scan");
            EFDataSet imageDataSet = new EFDataSet();
            imageDataSet.insertRowSet(imageRowSet);
            JParamObject paramObject = new JParamObject();
            // 设置存储类型：FILENET,FASTDFS
            String cclx = EnvironmentVariable.getProperty("CCLX", "FASTDFS");
            paramObject.setValue("CCLX", cclx);
            paramObject.setEnvValue("DBNO", EnvironmentVariable.getProperty("ImageUploadDBNO", "CWGXDBDEV"));
            paramObject.setEnvValue("DataBaseName", EnvironmentVariable.getProperty("ImageUploadDataBaseName", "CWGXDBDEV"));
            paramObject.setEnvValue("UserName", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
            paramObject.setEnvValue("UserCaption", EnvironmentVariable.getUserName());

            JResponseObject RO = null;
            try {
                RO = EAI.DAL.SVR(EnvironmentVariable.getProperty("ImageUploadSysImageSaveByte", "SYS_IMAGE_FN_SAVE_BYTE"), paramObject, imageDataSet);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (RO == null) {
                return 0;
            } else if (RO.getErrorCode() == 0) {
//                EFDataSet dataSet = (EFDataSet) RO.getResponseObject();
//                if (dataSet.getRowCount() <= 0) {
//                    return 0;
//                }
//                EFRowSet rowSet = dataSet.getRowSet(0);
//                Map<String, Object> map = new HashMap<String, Object>();
//                map = rowSet.getDataMap();
                return 1;
            } else {
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        } catch (JSONException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 使用poro的方式上传图片
     *
     * @param imgPath
     */
    public static JResponseObject uploadImgWithSVR2GX(String imgPath, String params) {

        EFRowSet imageRowSet = new EFRowSet();
        EAI.Protocol = EnvironmentVariable.getProperty("Protocol", "http");//http
        EAI.Server = EnvironmentVariable.getProperty("Server", "11.11.48.20");//11.11.48.20
        EAI.Port = EnvironmentVariable.getProperty("Port", "8001");//8001
        EAI.Path = EnvironmentVariable.getProperty("Path", "OSPServer");//OSPServer
        EAI.Service = EnvironmentVariable.getProperty("Service", "Android");//Android
        try {
            JSONObject jsonObject = new JSONObject(params);
            Iterator iterator = jsonObject.keys();
            while (iterator.hasNext()) {
                String key = iterator.next() + "";
                imageRowSet.putObject(key, jsonObject.get(key));
            }
            //byte[] data = FileUtils.FileToByte(imgPath);
            imageRowSet.putObject("imgByte", FileUtils.FileToByte(imgPath));
            imageRowSet.putString("F_MC", imgPath.substring(imgPath.lastIndexOf("/") + 1, imgPath.length()));
            imageRowSet.putString("F_SOURCE", "scan");
            EFDataSet imageDataSet = new EFDataSet();
            imageDataSet.insertRowSet(imageRowSet);
            JParamObject paramObject = new JParamObject();

            // 设置存储类型：FILENET,FASTDFS
            String cclx = EnvironmentVariable.getProperty("CCLX", "FASTDFS");
            paramObject.setValue("CCLX", cclx);
            paramObject.setEnvValue("DBNO", EnvironmentVariable.getProperty("ImageUploadDBNO", "CWGXDBDEV"));
            paramObject.setEnvValue("DataBaseName", EnvironmentVariable.getProperty("ImageUploadDataBaseName", "CWGXDBDEV"));
            paramObject.setEnvValue("UserName", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
            paramObject.setEnvValue("UserCaption", EnvironmentVariable.getUserName());
            JResponseObject RO = null;
            try {
                RO = EAI.DAL.SVR(EnvironmentVariable.getProperty("ImageUploadSysImageSaveByte", "SYS_IMAGE_FN_SAVE_BYTE"), paramObject, imageDataSet);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return RO;
//            if (RO == null) {
//                return 0;
//            } else if(RO.getErrorCode()==0){
//                return 1;
//            }else {
//                return 0;
//            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 使用poro的方式上传图片到个人空间，需要传用户信息
     *
     * @param imgPath
     */
    public static int uploadPrivateImgWithSVR(String imgPath) {

        EFRowSet imageRowSet = new EFRowSet();
//        http://11.11.48.20:8001/OSPServer/
        EAI.Protocol = EnvironmentVariable.getProperty("Protocol", "http");//http
        EAI.Server = EnvironmentVariable.getProperty("Server", "11.11.48.20");//11.11.48.20
        EAI.Port = EnvironmentVariable.getProperty("Port", "8001");//8001
        EAI.Path = EnvironmentVariable.getProperty("Path", "OSPServer");//OSPServer
        EAI.Service = EnvironmentVariable.getProperty("Service", "Android");//Android
        imageRowSet.putString("F_MC", imgPath.substring(imgPath.lastIndexOf("/") + 1, imgPath.length()));

        try {
            imageRowSet.putObject("imgByte", FileUtils.FileToByte(imgPath));
            imageRowSet.putString("F_SOURCE", "scan");
            EFDataSet imageDataSet = new EFDataSet();
            imageDataSet.insertRowSet(imageRowSet);
            JParamObject paramObject = new JParamObject();
            paramObject.setEnvValue("DBNO",  EnvironmentVariable.getProperty("ImageUploadDBNO", "CWGXDBDEV"));
            // 设置存储类型：FILENET,FASTDFS
            String cclx = EnvironmentVariable.getProperty("CCLX", "FASTDFS");
            paramObject.setValue("CCLX", cclx);
            paramObject.setEnvValue("DataBaseName",  EnvironmentVariable.getProperty("ImageUploadDataBaseName", "CWGXDBDEV"));
            paramObject.setEnvValue("UserName", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
            paramObject.setEnvValue("UserCaption", EnvironmentVariable.getUserName());
//            JResponseObject RO = EAI.DAL.SVR("SYS_IMAGE_PRIVATE_SAVE_BYTE", paramObject, imageDataSet);
            JResponseObject RO = null;
            try {
                RO = EAI.DAL.SVR(EnvironmentVariable.getProperty("ImageUploadSysImagePrivateSaveByte", "SYS_IMG_PRIVATE_FN_SAVE_BYTE"), paramObject, imageDataSet);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("RO", RO + "");
            if (RO == null) {
                return 0;
            } else if (RO.getErrorCode() == 0) {
//                EFDataSet dataSet = (EFDataSet) RO.getResponseObject();
//                if (dataSet.getRowCount() <= 0) {
//                    return 0;
//                }
//                EFRowSet rowSet = dataSet.getRowSet(0);
//                Map<String, Object> map = new HashMap<String, Object>();
//                map = rowSet.getDataMap();
//                EFDataSet returnDataSet = (EFDataSet) RO.getResponseObject();
//
//                List<ESPRowSet> list = returnDataSet.getRowSetList();
//                EFRowSet efRowSet = (EFRowSet) list.get(0);
//                Map<String,Object> map = (Map<String, Object>) efRowSet.getDataMap();

                return 1;
            } else {
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }
}
