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

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.url.NetRequestURL.newApi_dyrq;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigCallBack;
import com.tofly.ghrq_route.module.systemConfig.domain.ServerSysConfigBean;
import com.tofly.ghrq_route.common.util.net.volley.MultiPartStringRequest;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Amu on 2017/8/8.
 */

public class ServerSysConfigServiceImpl implements IServerSysConfigService {

    private Context mContext;

    private DBDaoHelper dbDaoHelper;

    public ServerSysConfigServiceImpl(Context context) {
        mContext = context;
        dbDaoHelper = DBDaoHelper.getInstance();
    }

    @Override
    public void getSysConfigList(final String token, final String key, final int pageindex, final int pagesize, final ServerSysConfigCallBack sysConfigCallBack) {
        String url = newApi_dyrq.getSysConfigListUrl() + "?key=" + key + "&current=" + pageindex + "&size=" + pagesize;
        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<ServerSysConfigBean> configList = 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<ServerSysConfigBean> configs = gson.fromJson(rowsArray, new TypeToken<List<ServerSysConfigBean>>() {
                        }.getType());
                        if (configs != null) {
                            configList = configs;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                            saveServerSysConfigs(configList, key);
                        }
                    } catch (Exception e) {
                        sysConfigCallBack.onGetSysConfigList(false, resCode, parseErrMsg, null, 0);
                    }
                }
                sysConfigCallBack.onGetSysConfigList(result, resCode, parseErrMsg, configList, total);
            } else {
                sysConfigCallBack.onGetSysConfigList(
                        false, responseCode.getCode(), responseCode.getMessage(), null, 0);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                sysConfigCallBack.onGetSysConfigList(
                        false, error.networkResponse.statusCode, errString, null, 0);
            } else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                sysConfigCallBack.onGetSysConfigList(
                        false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null, 0);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(mContext.getClass().getName(), postRequest);
    }

    private void saveServerSysConfigs(List<ServerSysConfigBean> sysConfigBeans, String config_type) {
        if (sysConfigBeans != null && sysConfigBeans.size() > 0) {
            dbDaoHelper.deleteAllServerConfigDatas(config_type);
            dbDaoHelper.saveServerConfigDatas(sysConfigBeans);
        }
    }

    @Override
    public void getSysSetting(final Context context, final ServerSysConfigCallBack sysConfigCallBack) {
        String url = newApi_dyrq.getSysSettingUrl();
        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.getResult();
                JsonObject configList = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                if (rowsArray != null) {
                    try {
                        Gson gson = new Gson();
                        JsonObject configs = gson.fromJson(rowsArray, new TypeToken<JsonObject>() {
                        }.getType());
                        if (configs != null) {
                            configList = configs;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                        }
                    } catch (Exception e) {
                        sysConfigCallBack.onGetSysSetting(false, resCode, parseErrMsg, null);
                    }
                }
                sysConfigCallBack.onGetSysSetting(result, resCode, parseErrMsg, configList);
            } else {
                sysConfigCallBack.onGetSysSetting(false, responseCode.getCode(), responseCode.getMessage(), null);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                sysConfigCallBack.onGetSysSetting(false, error.networkResponse.statusCode, errString, null);
            } else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                sysConfigCallBack.onGetSysSetting(false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                //参数拼装:表单提交方式
               return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(mContext.getClass().getName(), postRequest);
    }

    @Override
    public void uploadLocalSystemLogFiles(Context context, final List<String> files, final ServerSysConfigCallBack sysConfigCallBack) {
        String url = newApi_dyrq.getUploadLocalLogUrl();
        MultiPartStringRequest postRequest = new MultiPartStringRequest(Request.Method.POST,
                url, response -> {
                    URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                    if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                        sysConfigCallBack.onUploadLocalSystemLogFiles(true, responseCode.getCode(), responseCode.getMessage());
                    }else {
                        sysConfigCallBack.onUploadLocalSystemLogFiles(false, responseCode.getCode(), responseCode.getMessage());
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        sysConfigCallBack.onUploadLocalSystemLogFiles(false, error.networkResponse.statusCode, errString);
                    }else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        sysConfigCallBack.onUploadLocalSystemLogFiles(false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString);
                    }
                }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }

            @Override
            public Map<String, File> getFileUploads() {
                Map<String, File> params = new HashMap<>();
                if (files != null){
                    for (int i = 0; i < files.size(); i++){
                        String file = files.get(i);
                        params.put("file" + i, new File(file));
                    }
                }
                return params;
            }

/*            @Override
            public String getBodyContentType() {
                return JsonRequestConstant.PROTOCOL_FORM_DATA_CONTENT_TYPE;
            }*/
        };
        BaseApp.addMultiStatckRequest(context.getClass().getName(), postRequest);
    }
}
