package com.tofly.ghrq_route.module.survey.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.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.ErrorCode;
import com.tofly.ghrq_route.base.URLResponseCode.URLResponse;
import com.tofly.ghrq_route.module.survey.controller.SurveyCallBack;
import com.tofly.ghrq_route.module.survey.domain.SurveyBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.common.util.net.volley.MultiPartStringRequest;

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

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

public class SurveyServiceImpl implements ISurveyService {

    @Override
    public void getSurveyList(Context context, int select_state, int work_state, String keyword, int pageindex, int pagesize, SurveyCallBack surveyCallBack) {
        String url = newApi_dyrq.getSurveyListUrl() + "?current=" + pageindex + "&size=" + pagesize + "&orders[0].asc=false&orders[0].column=create_time";
        String userid = BaseApp.getInstance().getUserId();
        if (userid != null && !userid.isEmpty()) {
            switch (select_state) {
                case 0: {
                    url += "&state=1";
                }
                break;
                case 1: {
                    url += "&state=2";
                }
                break;
                default: {
                    if (work_state > 0) {
                        url += "&workOrderState=" + work_state;
                    }
                    if (keyword != null && !keyword.isEmpty()) {
                        url += "&address=" + keyword;
                    }
                }
                break;
            }
        }
        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<SurveyBean> surveyList = 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<SurveyBean> surveyBeans = gson.fromJson(rowsArray, new TypeToken<List<SurveyBean>>(){}.getType());
                        if (surveyBeans != null && surveyBeans.size() >= 0){
                            surveyList = surveyBeans;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                            //saveTroubles(troubleBeanList);
                        }
                    }catch (Exception e){
                        surveyCallBack.onGetDatas(false, resCode, parseErrMsg, null, 0);
                    }
                }
                surveyCallBack.onGetDatas(result, resCode, parseErrMsg, surveyList, total);
            }else {
                surveyCallBack.onGetDatas(
                        false, responseCode.getCode(), responseCode.getMessage(), null, 0);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                try {
                    String errString = new String(error.networkResponse.data, "UTF-8");
                    surveyCallBack.onGetDatas(
                            false, error.networkResponse.statusCode, errString, null, 0);
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    surveyCallBack.onGetDatas(
                            false, error.networkResponse.statusCode, null, null, 0);
                }
            }else {
                String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                surveyCallBack.onGetDatas(
                        false, ErrorCode.HTTPCONN_TIMEOUT, errString, null, 0);
            }
        }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };

        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }

    @Override
    public void addSurveyBefore(Context context, SurveyBean surveyBean, List<TroublePictureBean> photos, List<TroubleAudioBean> audios,
                                List<TroubleAudioBean> files, SurveyCallBack surveyCallBack) {
        String url = newApi_dyrq.getSurveyBeforeUploadUrl();
        MultiPartStringRequest postRequest = new MultiPartStringRequest(Request.Method.POST,
                url, response -> {
            URLResponse responseCode = new URLResponse(response);
            if (responseCode.getCode() == ErrorCode.SUCCESS){
                surveyCallBack.onSetData(true, responseCode.getCode(), responseCode.getMessage());
            }else {
                surveyCallBack.onSetData(false, responseCode.getCode(), responseCode.getMessage());
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                try {
                    String errString = new String(error.networkResponse.data, "UTF-8");
                    surveyCallBack.onSetData(false, error.networkResponse.statusCode, errString);
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    surveyCallBack.onSetData(false, error.networkResponse.statusCode, null);
                }
            }else {
                String errString = ErrorCode.getErrorMessage(ErrorCode.HTTPCONN_TIMEOUT);
                surveyCallBack.onSetData(false, ErrorCode.HTTPCONN_TIMEOUT, errString);
            }
        }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                Map<String, String> headerParams = newApi_dyrq.getHeaderParams();
                headerParams.put("Charset", "utf-8");
                return headerParams;
            }

            @Override
            public Map<String, String> getStringUploads() {
                Map<String, String> params = new HashMap<>();
                /*工程名称*/
                String name = surveyBean.getName();
                params.put("name", name);
                /*联系人*/
                String contactPeople = surveyBean.getContacts();
                params.put("contacts", contactPeople);
                /*联系电话*/
                String phone = surveyBean.getContactsNumber();
                params.put("contactsNumber", phone);
                /*地址*/
                String addr = surveyBean.getBuriedAddress();
                params.put("buriedAddress", addr);
                /*户数*/
                int houseHolds = surveyBean.getHouseHolds();
                params.put("houseHolds", houseHolds + "");
                /*调压器编号*/
                String adjustCode = surveyBean.getCode();
                if (adjustCode != null && !adjustCode.isEmpty())
                    params.put("code", adjustCode);
                /*新增设备数量*/
                int deviceNum = surveyBean.getAddDeviceNum();
                params.put("addDeviceNum", deviceNum + "");
                /*工程性质*/
                int type = surveyBean.getType();
                params.put("type", type + "");
                /*设备类型*/
                int addDeviceType = surveyBean.getAddDevice();
                params.put("addDevice", addDeviceType + "");
                /*有无埋地管*/
                int isBuried = surveyBean.getIsBuried();
                params.put("isBuried", isBuried + "");
                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();
                        String key = "photo" + count + "," + 0 + "," + time;
                        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 = "audio" + count + "," + second + "," + time;;
                        if (file != null && !file.isEmpty()){
                            params.put(key, new File(file));
                        }
                    }
                }
                if (files != null && files.size() > 0){
                    for (int i = 0; i < files.size(); i++, count++){
                        TroubleAudioBean audioBean = files.get(i);
                        String file = audioBean.getPath();
                        String time = audioBean.getCreateTime();
                        String key = "other" + count + "," + 0 + "," + time;;
                        if (file != null && !file.isEmpty()){
                            params.put(key, new File(file));
                        }
                    }
                }

                return params;
            }
        };
        BaseApp.addMultiStatckRequest(context.getClass().getName(), postRequest);
    }
}
