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

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
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.url.NetRequestURL.newApi_dyrq;
import com.tofly.ghrq_route.base.URLResponseCode.URLResponse;
import com.tofly.ghrq_route.base.URLResponseCode.ErrorCode;
import com.tofly.ghrq_route.module.troubleType.TroubleTypeDaoHelper;
import com.tofly.ghrq_route.module.troubleType.controller.TroubleTypeCallBack;
import com.tofly.ghrq_route.module.troubleType.domain.PipeTypeBean;
import com.tofly.ghrq_route.module.troubleType.domain.SysDeviceTypeBean;
import com.tofly.ghrq_route.module.troubleType.domain.TroubleRiskLevelBean;
import com.tofly.ghrq_route.module.troubleType.domain.TroubleTypeBean;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class TroubleTypeServiceImpl implements ITroubleTypeService {
    private Context mContext;

    private TroubleTypeDaoHelper dbDaoHelper;

    public TroubleTypeServiceImpl(Context context) {
        mContext = context;
        dbDaoHelper = TroubleTypeDaoHelper.getInstance();
    }

    @Override
    public void getSysDeviceTypeList(final String token, final TroubleTypeCallBack troubleTypeCallBack) {
        String url = NetRequestURL.getSysDeviceTypeListUrl();
        StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, response -> {
                    URLResponse responseCode = new URLResponse(response);
                    if (responseCode.getCode() == ErrorCode.SUCCESS) {
                        String rowsArray = responseCode.queryResult("rows");
                        List<SysDeviceTypeBean> deviceTypeList = null;
                        int resCode = -1;
                        boolean result = false;
                        String parseErrMsg = "用户解析失败";
                        if (rowsArray != null) {
                            try {
                                Gson gson = new Gson();
                                List<SysDeviceTypeBean> equipments = gson.fromJson(rowsArray, new TypeToken<List<SysDeviceTypeBean>>() {
                                }.getType());
                                if (equipments != null && equipments.size() > 0) {
                                    deviceTypeList = equipments;
                                    resCode = responseCode.getCode();
                                    parseErrMsg = responseCode.getMessage();
                                    result = true;
                                    saveSysDeviceTypes(deviceTypeList);
                                }
                            } catch (Exception e) {
                                troubleTypeCallBack.onGetSysDeviceTypeList(false, resCode, parseErrMsg, null);
                            }
                        }
                        troubleTypeCallBack.onGetSysDeviceTypeList(result, resCode, parseErrMsg, deviceTypeList);
                    } else {
                        troubleTypeCallBack.onGetSysDeviceTypeList(
                                false, responseCode.getCode(), responseCode.getMessage(), null);
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        troubleTypeCallBack.onGetSysDeviceTypeList(
                                false, error.networkResponse.statusCode, errString, null);
                    } else {
                        String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                        troubleTypeCallBack.onGetSysDeviceTypeList(
                                false, ErrorCode.HTTPCONN_TIMEOUT, errString, null);
                    }
                }) {

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

    private void saveSysDeviceTypes(List<SysDeviceTypeBean> sysDeviceTypeBeans) {
        if (sysDeviceTypeBeans != null && sysDeviceTypeBeans.size() > 0) {
            dbDaoHelper.saveSysDeviceTypes(sysDeviceTypeBeans);
        }
    }

    @Override
    public void getTroubleTypeList(Context context, int pageindex, int pagesize, final TroubleTypeCallBack troubleTypeCallBack) {
        String url = newApi_dyrq.getTroubleTypeListUrl() + "?current=" + pageindex + "&size=" + pagesize;
        StringRequest postRequest = new StringRequest(Request.Method.GET,
                url, response -> {
            URLResponse responseCode = new URLResponse(response);
            if (responseCode.getCode() == ErrorCode.SUCCESS) {
                String rowsArray = responseCode.queryResult("records");
                List<TroubleTypeBean> troubleTypeList = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                if (rowsArray != null) {
                    try {
                        Gson gson = new Gson();
                        List<TroubleTypeBean> troubleTypes = gson.fromJson(rowsArray, new TypeToken<List<TroubleTypeBean>>() {}.getType());
                        if (troubleTypes != null && troubleTypes.size() > 0) {
                            troubleTypeList = troubleTypes;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                            saveSysTroubleTypes(troubleTypeList);
                        }
                    } catch (Exception e) {
                        troubleTypeCallBack.onGetTroubleTypeList(false, resCode, parseErrMsg, null);
                    }
                }
                troubleTypeCallBack.onGetTroubleTypeList(result, resCode, parseErrMsg, troubleTypeList);
            } else {
                troubleTypeCallBack.onGetTroubleTypeList(
                        false, responseCode.getCode(), responseCode.getMessage(), null);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                troubleTypeCallBack.onGetTroubleTypeList(
                        false, error.networkResponse.statusCode, errString, null);
            } else {
                String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                troubleTypeCallBack.onGetTroubleTypeList(
                        false, ErrorCode.HTTPCONN_TIMEOUT, errString, null);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }

    private void saveSysTroubleTypes(List<TroubleTypeBean> troubleTypeBeans) {
        if (troubleTypeBeans != null && troubleTypeBeans.size() > 0) {
            dbDaoHelper.saveSysTroubleTypes(troubleTypeBeans);
        }
    }

    @Override
    public void getTroubleRiskLevelList(Context context, int pageindex, int pagesize, TroubleTypeCallBack troubleTypeCallBack) {
        String url = newApi_dyrq.getTroubleLevelListUrl() + "?current=" + pageindex + "&size=" + pagesize;
        StringRequest postRequest = new StringRequest(Request.Method.GET,
                url, response -> {
            URLResponse responseCode = new URLResponse(response);
            if (responseCode.getCode() == ErrorCode.SUCCESS) {
                String rowsArray = responseCode.queryResult("records");
                List<TroubleRiskLevelBean> troubleLevelList = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                if (rowsArray != null) {
                    try {
                        Gson gson = new Gson();
                        List<TroubleRiskLevelBean> troubleLevels = gson.fromJson(rowsArray, new TypeToken<List<TroubleRiskLevelBean>>() {
                        }.getType());
                        if (troubleLevels != null && troubleLevels.size() > 0) {
                            troubleLevelList = troubleLevels;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                            saveSysTroubleRiskLevels(troubleLevelList);
                        }
                    } catch (Exception e) {
                        troubleTypeCallBack.onGetTroubleRiskLevelList(false, resCode, parseErrMsg, null);
                    }
                }
                troubleTypeCallBack.onGetTroubleRiskLevelList(result, resCode, parseErrMsg, troubleLevelList);
            } else {
                troubleTypeCallBack.onGetTroubleRiskLevelList(
                        false, responseCode.getCode(), responseCode.getMessage(), null);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                troubleTypeCallBack.onGetTroubleRiskLevelList(
                        false, error.networkResponse.statusCode, errString, null);
            } else {
                String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                troubleTypeCallBack.onGetTroubleRiskLevelList(
                        false, ErrorCode.HTTPCONN_TIMEOUT, errString, null);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }

    private void saveSysTroubleRiskLevels(List<TroubleRiskLevelBean> levelBeans) {
        if (levelBeans != null && levelBeans.size() > 0) {
            dbDaoHelper.saveSysTroubleLevels(levelBeans);
        }
    }

    @Override
    public void getPipeTypeList(Context context, int pageindex, int pagesize, TroubleTypeCallBack troubleTypeCallBack) {
        String url = newApi_dyrq.getPipeTypeListUrl() + "?current=" + pageindex + "&size=" + pagesize;
        StringRequest postRequest = new StringRequest(Request.Method.GET,
                url, response -> {
            URLResponse responseCode = new URLResponse(response);
            if (responseCode.getCode() == ErrorCode.SUCCESS) {
                String rowsArray = responseCode.queryResult("records");
                List<PipeTypeBean> pipeTypeList = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                if (rowsArray != null) {
                    try {
                        Gson gson = new Gson();
                        List<PipeTypeBean> pipeTypes = gson.fromJson(rowsArray, new TypeToken<List<PipeTypeBean>>() {}.getType());
                        if (pipeTypes != null && pipeTypes.size() > 0) {
                            pipeTypeList = pipeTypes;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                            savePipeTypes(pipeTypeList);
                        }
                    } catch (Exception e) {
                        troubleTypeCallBack.onGetPipeTypeList(false, resCode, parseErrMsg, null);
                    }
                }
                troubleTypeCallBack.onGetPipeTypeList(result, resCode, parseErrMsg, pipeTypeList);
            } else {
                troubleTypeCallBack.onGetPipeTypeList(
                        false, responseCode.getCode(), responseCode.getMessage(), null);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                troubleTypeCallBack.onGetPipeTypeList(
                        false, error.networkResponse.statusCode, errString, null);
            } else {
                String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                troubleTypeCallBack.onGetPipeTypeList(
                        false, ErrorCode.HTTPCONN_TIMEOUT, errString, null);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }

    private void savePipeTypes(List<PipeTypeBean> pipeTypes) {
        if (pipeTypes != null && pipeTypes.size() > 0) {
            dbDaoHelper.savePipeTypes(pipeTypes);
        }
    }
}
