package com.tofly.ghrq_route.module.sketch.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.mgq.base.utils.string.StringUtil;
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.sketch.SketchDaoHelper;
import com.tofly.ghrq_route.module.sketch.controller.SketchCallback;
import com.tofly.ghrq_route.module.sketch.domain.SketchBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
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;

public class SketchServiceImpl implements ISketchService {
    private SketchDaoHelper sketchDaoHelper;

    public SketchServiceImpl() {
        sketchDaoHelper = SketchDaoHelper.getInstance();
    }

    @Override
    public void getSketchList(Context context, String userid, int sketch_state, int pageindex, int pagesize, SketchCallback sketchCallback) {
        String url = newApi_dyrq.getSketchListUrl()
                + "?current=" + pageindex + "&size=" + pagesize + "&creatorid=" + 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<SketchBean> sketchList = 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<SketchBean> sketchBeans = gson.fromJson(rowsArray, new TypeToken<List<SketchBean>>(){}.getType());
                                if (sketchBeans != null) {
                                    sketchList = sketchBeans;
                                    resCode = responseCode.getCode();
                                    parseErrMsg = responseCode.getMessage();
                                    result = true;

                                    saveSketchList(sketchList);
                                }
                            } catch (Exception e) {
                                sketchCallback.onGetSketchList(false, resCode, parseErrMsg, null, 0);
                            }
                        }
                        sketchCallback.onGetSketchList(result, resCode, parseErrMsg, sketchList, total);
                    } else {
                        sketchCallback.onGetSketchList(
                                false, responseCode.getCode(), responseCode.getMessage(), null, 0);
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        sketchCallback.onGetSketchList(
                                false, error.networkResponse.statusCode, errString, null, 0);
                    } else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        sketchCallback.onGetSketchList(
                                false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null, 0);
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() {
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }

    /**
     * 保存从服务器上获取的草图列表，先删除本地的记录(不包括未提交的草图)
     * @param sketchBeans 获取的草图
     * */
    private void saveSketchList(List<SketchBean> sketchBeans) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (sketchBeans != null && userBean != null) {
            String userid = userBean.getUserid();
            sketchDaoHelper.deleteSketchBeans(userid, SketchBean.SKETCH_TASK_STATUS.SKETCH_TASK_COMMITED.getStatus());
            sketchDaoHelper.deleteSketchBeans(userid, SketchBean.SKETCH_TASK_STATUS.SKETCH_TASK_HANDLED.getStatus());
            for (SketchBean sketchBean : sketchBeans) {
                sketchBean.setUserid(userid);
                sketchDaoHelper.insertOrUpdateSketchBean(sketchBean);
            }
        }
    }

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

            @Override
            public Map<String, String> getStringUploads() {
                Map<String, String> params = new HashMap<>();
                params.put("caption", sketchBean.getCaption());
                params.put("content", sketchBean.getContent());
                params.put("scale", StringUtil.formatDigit(sketchBean.getScale(), 2));
                params.put("x", StringUtil.formatDigit6(sketchBean.getX()));
                params.put("y", StringUtil.formatDigit6(sketchBean.getY()));
                return params;
            }

            @Override
            public Map<String, File> getFileUploads() {
                Map<String, File> params = new HashMap<>();
                String file = sketchBean.getFilepath();
                if (file != null && !file.isEmpty()) {
                    String key = "file";
                    params.put(key, new File(file));
                }
                return params;
            }
        };
        BaseApp.addMultiStatckRequest(context.getClass().getName(), postRequest);
    }

    @Override
    public void getSketchData(Context context, String sketch_id, SketchCallback sketchCallback) {
        String url = newApi_dyrq.getSketchDataUrl() + sketch_id;
        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();
                String fileids = responseCode.queryResult("fileids");
                SketchBean sketchBean = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                if (rowsArray != null) {
                    try {
                        Gson gson = new Gson();
                        SketchBean sketch = gson.fromJson(rowsArray, new TypeToken<SketchBean>(){}.getType());
                        if (sketch != null) {
                            sketchBean = sketch;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;

                            if (fileids != null && !fileids.isEmpty()) {
                                List<String> files = gson.fromJson(fileids, new TypeToken<List<String>>(){}.getType());
                                if (files != null) {
                                    /*保存工单图片*/
                                }
                            }

                            /*保存工单详情*/
                            saveSketchData(sketchBean);
                        }
                    } catch (Exception e) {
                        sketchCallback.onGetSketchData(false, resCode, parseErrMsg, null);
                    }
                }
                sketchCallback.onGetSketchData(result, resCode, parseErrMsg, sketchBean);
            } else {
                sketchCallback.onGetSketchData(
                        false, responseCode.getCode(), responseCode.getMessage(), null);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                sketchCallback.onGetSketchData(
                        false, error.networkResponse.statusCode, errString, null);
            } else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                sketchCallback.onGetSketchData(
                        false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() {
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest);
    }

    /**
     * 保存从服务器上获取的草图详情
     * @param sketchBean 获取的草图
     * */
    private void saveSketchData(SketchBean sketchBean) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (sketchBean != null && userBean != null) {
            String userid = userBean.getUserid();
            sketchBean.setUserid(userid);
            sketchDaoHelper.insertOrUpdateSketchBean(sketchBean);
        }
    }
}
