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

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.module.uploadFile.controller.UploadFileCallBack;
import com.tofly.ghrq_route.module.uploadFile.domain.UploadFileBean;
import com.tofly.ghrq_route.common.util.net.volley.MultiPartStringRequest;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Amu on 2017/3/13.
 */

public class UploadFileServiceImpl implements IUploadFileService {
    private Context mContext;

    public UploadFileServiceImpl(Context context){
        mContext = context;
    }

    @Override
    public void getUploadFileList(final String token, final String tableId, String table_name, final int pageindex, final int pagesize, final UploadFileCallBack uploadFileCallBack) {
        String url = NetRequestURL.getUploadFileListUrl();
        StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                    String rowsArray = responseCode.queryResult("rows");
                    List<UploadFileBean> fileBeanList = null;
                    int resCode = -1;
                    boolean result = false;
                    String parseErrMsg = "用户解析失败";
                    if (rowsArray != null){
                        try {
                            Gson gson = new Gson();
                            UploadFileBean[] fileBeens = gson.fromJson(rowsArray, UploadFileBean[].class);
                            if (fileBeens != null && fileBeens.length >= 0){
                                fileBeanList = Arrays.asList(fileBeens);
                                resCode = responseCode.getCode();
                                parseErrMsg = responseCode.getMessage();
                                result = true;
                            }
                        }catch (Exception e){
                            uploadFileCallBack.onGetUploadFileList(false, resCode, parseErrMsg, null);
                        }
                    }
                    uploadFileCallBack.onGetUploadFileList(result, resCode, parseErrMsg, fileBeanList);
                }else {
                    uploadFileCallBack.onGetUploadFileList(
                            false, responseCode.getCode(), responseCode.getMessage(), null);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //登录失败
                if (error.networkResponse != null) {
                    try {
                        String errString = new String(error.networkResponse.data, "UTF-8");
                        uploadFileCallBack.onGetUploadFileList(
                                false, error.networkResponse.statusCode, errString, null);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        uploadFileCallBack.onGetUploadFileList(
                                false, error.networkResponse.statusCode, null, null);
                    }
                }else {
                    String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                    uploadFileCallBack.onGetUploadFileList(
                            false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null);
                }
            }
        }){
            @Override
            protected Map<String, String> getParams(){
                //参数拼装:表单提交方式
                Map<String, String> params = new HashMap<String, String>();
                params.put("tableid", tableId);
                params.put("pageindex", pageindex + "");
                params.put("pagesize", pagesize + "");
                return params;
            }

            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", token);
                return params;
            }
        };
        BaseApp.addRequest(mContext.getClass().getName(), postRequest);
    }

    @Override
    public void addUploadFile(final String token, final String tableId, final String filepath, final String filenote, final int audiolenth, final String createTime, final UploadFileCallBack uploadFileCallBack) {
        String url = NetRequestURL.getAddUploadFileUrl();
        MultiPartStringRequest postRequest = new MultiPartStringRequest(Request.Method.POST,
                url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                    String responseResult = responseCode.getResult();
                    int resCode = -1;
                    boolean result = false;
                    String parseErrMsg = "用户解析失败";
                    UploadFileBean upfile = null;
                    if (responseResult != null){
                        try {
                            Gson gson = new Gson();
                            UploadFileBean fileBeen = gson.fromJson(responseResult, UploadFileBean.class);
                            if (fileBeen != null){
                                upfile = fileBeen;
                                resCode = responseCode.getCode();
                                parseErrMsg = responseCode.getMessage();
                                result = true;
                            }
                        }catch (Exception e){
                            uploadFileCallBack.onAddUploadFile(false, resCode, parseErrMsg, null);
                        }
                    }
                    uploadFileCallBack.onAddUploadFile(true, responseCode.getCode(), responseCode.getMessage(), upfile);
                }else {
                    uploadFileCallBack.onAddUploadFile(false, responseCode.getCode(), responseCode.getMessage(), null);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //登录失败
                if (error.networkResponse != null) {
                    try {
                        String errString = new String(error.networkResponse.data, "UTF-8");
                        uploadFileCallBack.onAddUploadFile(false, error.networkResponse.statusCode, errString, null);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        uploadFileCallBack.onAddUploadFile(false, error.networkResponse.statusCode, null, null);
                    }
                }else {
                    String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                    uploadFileCallBack.onAddUploadFile(false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null);
                }
            }
        }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", token);
                return params;
            }

            @Override
            public Map<String, String> getStringUploads() {
                Map<String, String> params = new HashMap<>();
                params.put("tableid", tableId);
                if (filenote != null && !filenote.isEmpty())
                    params.put("filenote", filenote);
                if (audiolenth >= 0)
                    params.put("audiolength", audiolenth + "");
                if (createTime != null && !createTime.isEmpty()){
                    params.put("check_time", createTime);
                }
                return params;
            }

            @Override
            public Map<String, File> getFileUploads() {
                Map<String, File> params = new HashMap<>();
                String strFiles = filepath;
                if (strFiles != null && !strFiles.isEmpty()){
                    String[] files = strFiles.split(",");
                    if (files != null && files.length > 0){
                        for (int i = 0; i < files.length; i++){
                            String key = "file" + i;
                            String value = files[i];
                            params.put(key, new File(value));
                        }
                    }
                }
                return params;
            }
        };
        BaseApp.addMultiStatckRequest(mContext.getClass().getName(), postRequest);
    }

    @Override
    public void removeUploadFile(final String token, String fileid, final UploadFileCallBack uploadFileCallBack) {
        String url = NetRequestURL.getDeleteUploadFileUrl() + fileid;
        StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                    uploadFileCallBack.onRemoveUploadFile(true, responseCode.getCode(), responseCode.getMessage());
                }else {
                    uploadFileCallBack.onRemoveUploadFile(false, responseCode.getCode(), responseCode.getMessage());
                }
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                try {
                    String errString = new String(error.networkResponse.data, "UTF-8");
                    uploadFileCallBack.onRemoveUploadFile(false, error.networkResponse.statusCode, errString);
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    uploadFileCallBack.onRemoveUploadFile(false, error.networkResponse.statusCode, null);
                }
            }else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                uploadFileCallBack.onRemoveUploadFile(false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString);
            }
        }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", token);
                return params;
            }
        };
        BaseApp.addRequest(mContext.getClass().getName(), postRequest);
    }
}
