package com.tofly.ghrq_route.module.uploadPhoto.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.google.gson.reflect.TypeToken;
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.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.uploadPhoto.controller.UploadPhotoCallBack;
import com.tofly.ghrq_route.module.uploadPhoto.domain.ReportedPhotoBean;
import com.tofly.ghrq_route.module.uploadPhoto.domain.UploadPhotoBean;
import com.tofly.ghrq_route.common.util.net.volley.MultiPartStringRequest;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class UploadPhotoServiceImpl implements IUploadPhotoService {
    private Context mContext;

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

    @Override
    public void addUploadPhotoPhoto(final String token, final String photoId, final String file, final int pictype, final int second, final String time, final UploadPhotoCallBack uploadPhotoCallBack) {
        String url = NetRequestURL.getUploadPhotoPhotoUrl();
        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){
                    uploadPhotoCallBack.onAddUploadPhotoPhoto(true, responseCode.getCode(), responseCode.getMessage(), photoId);
                }else {
                    uploadPhotoCallBack.onAddUploadPhotoPhoto(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");
                        uploadPhotoCallBack.onAddUploadPhotoPhoto(false, error.networkResponse.statusCode, errString, null);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        uploadPhotoCallBack.onAddUploadPhotoPhoto(false, error.networkResponse.statusCode, null, null);
                    }
                }else {
                    String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                    uploadPhotoCallBack.onAddUploadPhotoPhoto(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", photoId);
                params.put("pictype", pictype + "");
                params.put("audiolength", second + "");
                params.put("check_time", time);
                return params;
            }

            @Override
            public Map<String, File> getFileUploads() {
                Map<String, File> params = new HashMap<>();
                params.put("file", new File(file));
                return params;
            }
        };
        BaseApp.addMultiStatckRequest(mContext.getClass().getName(), postRequest);
    }

    @Override
    public void addUploadPhotoNew(final String token, final UploadPhotoBean photoBean, final List<TroublePictureBean> photos, final List<TroubleAudioBean> audios, final UploadPhotoCallBack uploadPhotoCallBack) {
        String url = NetRequestURL.newApi_dyrq.getUploadPhotoUrl();
        MultiPartStringRequest postRequest = new MultiPartStringRequest(Request.Method.POST,
                url, response -> {
                    URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                    if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                        uploadPhotoCallBack.onAddUploadPhotoInfo(true, responseCode.getCode(), responseCode.getMessage(), null);
                    }else {
                        uploadPhotoCallBack.onAddUploadPhotoInfo(false, responseCode.getCode(), responseCode.getMessage(), null);
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        uploadPhotoCallBack.onAddUploadPhotoInfo(false, error.networkResponse.statusCode, errString, null);
                    }else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        uploadPhotoCallBack.onAddUploadPhotoInfo(false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null);
                    }
                }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return NetRequestURL.newApi_dyrq.getHeaderParams();
            }

            @Override
            public Map<String, String> getStringUploads() {
                Map<String, String> params = new HashMap<>();
                params.put("lng", photoBean.getLng());
                params.put("lat", photoBean.getLat());
                params.put("flag", photoBean.getGpsFlag() + "");
                String addr = photoBean.getAddr();
                if (addr != null && !addr.isEmpty())
                    params.put("address", addr);
                String picTypeId = photoBean.getPicTypeId();
                if (picTypeId != null && !picTypeId.isEmpty()){
                    params.put("pictypeid", picTypeId);
                }
                String notes = photoBean.getNotes();
                if (notes != null && !notes.isEmpty())
                    params.put("description", notes);
                return params;
            }

            @Override
            public Map<String, File> getFileUploads() {
                Map<String, File> params = new HashMap<>();
                int count = 1;
                if (photos != null && photos.size() > 0){
                    for (int i = 0; i < photos.size(); i++, count++){
                        TroublePictureBean pictureBean = photos.get(i);
                        String file = pictureBean.getFilepath();
                        String time = pictureBean.getCreateTime();
                        long second = pictureBean.getSecond() / 1000;
                        String key = "file" + count + "," + second + "," + time;
                        //String key = "file" + count ;
                        if (file != null && !file.isEmpty())
                            params.put(key, new File(file));
                    }
                }
                if (audios != null && audios.size() > 0){
                    for (int i = 0; i < audios.size(); i++, count++){
                        TroubleAudioBean audioBean = audios.get(i);
                        String file = audioBean.getPath();
                        /*int second = audioBean.getSecond();
                        String time = audioBean.getCreateTime();
                        String key = "file" + count + "," + second + "," + time;*/
                        String key = "file" + count ;
                        if (file != null && !file.isEmpty()){
                            params.put(key, new File(file));
                        }
                    }
                }
                return params;
            }
        };
        BaseApp.addMultiStatckRequest(mContext.getClass().getName(), postRequest);
    }

    @Override
    public void getReportedPhoto(Context context, String picTypeId, String departId, String userId, int pageindex, int pagesize, UploadPhotoCallBack uploadPhotoCallBack) {
        String url = NetRequestURL.newApi_dyrq.getReportedPhotoUrl() + "?current=" + pageindex + "&size=" + pagesize
                + "&orders[0].asc=false&orders[0].column=CREATE_TIME";
        if (picTypeId != null) {
            url += "&pictypeid=" + picTypeId;
        }
        if (departId != null) {
            url += "&companyid=" + departId;
        }
        if (userId != null) {
            url += "&uploadUserid=" + userId;
        }

        StringRequest postRequest = new StringRequest(Request.Method.GET,
                url, response -> {
            URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
            if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                String rowsArray = responseCode.queryResult("records");
                List<ReportedPhotoBean> photoList = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                int total = 0;
                String strTotal = responseCode.queryResult("total");
                if (strTotal != null && !strTotal.isEmpty()){
                    total = Integer.parseInt(strTotal);
                }
                if (rowsArray != null){
                    try {
                        Gson gson = new Gson();
                        List<ReportedPhotoBean> photos = gson.fromJson(rowsArray, new TypeToken<List<ReportedPhotoBean>>(){}.getType());
                        if (photos != null && photos.size() >= 0){
                            photoList = photos;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                            //saveTroubles(troubleBeanList);
                        }
                    }catch (Exception e){
                        uploadPhotoCallBack.onGetReportedPhoto(false, resCode, parseErrMsg, null, 0);
                    }
                }
                uploadPhotoCallBack.onGetReportedPhoto(result, resCode, parseErrMsg, photoList, total);
            }else {
                uploadPhotoCallBack.onGetReportedPhoto(false, responseCode.getCode(), responseCode.getMessage(), null, 0);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                try {
                    String errString = new String(error.networkResponse.data, "UTF-8");
                    uploadPhotoCallBack.onGetReportedPhoto(
                            false, error.networkResponse.statusCode, errString, null, 0);
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    uploadPhotoCallBack.onGetReportedPhoto(
                            false, error.networkResponse.statusCode, null, null, 0);
                }
            }else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                uploadPhotoCallBack.onGetReportedPhoto(
                        false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null, 0);
            }
        }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return NetRequestURL.newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }
}
