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

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
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.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
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.deviceInfo.domain.DeviceInfoBean;
import com.tofly.ghrq_route.module.sign.controller.SignCallBack;
import com.tofly.ghrq_route.module.sign.domain.SignAttendedDataBean;
import com.tofly.ghrq_route.module.sign.domain.SignHistoryDataBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.common.util.net.volley.JsonRequestConstant;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

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

public class SignServiceImpl implements ISignService {
    private Context mContext;
    private DBDaoHelper dbDaoHelper;

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

    @Override
    public void getSignStatusToday(Context context, String userid, final SignCallBack signCallBack) {
        String url = newApi_dyrq.getLastSignStatusUrl();
        StringRequest postRequest = new StringRequest(Request.Method.GET,
                url, response -> {
                    URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                    int signState = -1;
                    if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                        String resResult = responseCode.queryResult("state");
                        String strSection = responseCode.queryResult("section");
                        int section = 0;
                        int resCode = -1;
                        boolean result = false;
                        String parseErrMsg = "用户解析失败";
                        if (resResult != null && !resResult.isEmpty() ){
                            signState = Integer.parseInt(resResult);
                            if (strSection != null && !strSection.isEmpty()) {
                                section = Integer.parseInt(strSection);
                            }
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;
                        }
                        signCallBack.onGetSignStatusToday(result, resCode, parseErrMsg, signState, section);
                    }else {
                        signCallBack.onGetSignStatusToday(false, responseCode.getCode(), responseCode.getMessage(), signState, -1);
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        signCallBack.onGetSignStatusToday(false, error.networkResponse.statusCode, errString, -1, -1);
                    }else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        signCallBack.onGetSignStatusToday(false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, -1, -1);
                    }
                }){

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

    @Override
    public void getSignListToday(Context context, final String userid, final int pageindex, final int pagesize, final SignCallBack signCallBack) {
        String url = newApi_dyrq.getSignListUrl() + "?current=" + pageindex + "&size=" + pagesize + "&userId=" + userid
                + "&isToday=true"
                + "&orders[0].asc=true&orders[0].column=SIGN_TIME";
        StringRequest postRequest = new StringRequest(Request.Method.GET,
                url, response -> {
                    URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                    if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                        String resResult = responseCode.queryResult("records");
                        int resCode = -1;
                        boolean result = false;
                        List<SignHistoryDataBean> signDataList = null;
                        String parseErrMsg = "用户解析失败";
                        int total = 0;
                        String strTotal = responseCode.queryResult("total");
                        if (strTotal != null && !strTotal.isEmpty()) {
                            total = Integer.parseInt(strTotal);
                        }
                        if (resResult != null){
                            try {
                                Gson gson = new Gson();
                                List<SignHistoryDataBean> signDatas = gson.fromJson(resResult, new TypeToken<List<SignHistoryDataBean>>(){}.getType());
                                if (signDatas != null && signDatas.size() >= 0){
                                    signDataList = signDatas;
                                    resCode = responseCode.getCode();
                                    parseErrMsg = responseCode.getMessage();
                                    result = true;
                                    saveSignListToday(userid, signDataList);
                                }
                            }catch (Exception e){
                                signCallBack.onGetSignListToday(false, resCode, parseErrMsg, null, 0);
                            }
                        }
                        signCallBack.onGetSignListToday(result, resCode, parseErrMsg, signDataList, total);
                    }else {
                        signCallBack.onGetSignListToday(false, responseCode.getCode(), responseCode.getMessage(), null, 0);
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        signCallBack.onGetSignListToday(false, error.networkResponse.statusCode, errString, null, 0);
                    }else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        signCallBack.onGetSignListToday(false, URLResponseCode.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 signToday(Context context, String userid, final SignHistoryDataBean signHistory, final DeviceInfoBean deviceInfo, final List<String> localPlanIds, final SignCallBack signCallBack) {
        String url = newApi_dyrq.getSignAddUrl();
        StringRequest postRequest = new StringRequest(Request.Method.POST,
                url, response -> {
                    URLResponseCode.URLResponse urlResponse = new URLResponseCode.URLResponse(response);
                    if (urlResponse.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                        int section = 0;
                        int plan_num = 0;
                        List<String> listPlanId = null;
                        String strSection = urlResponse.queryResult("section");
                        if (strSection != null && !strSection.isEmpty()) {
                            section = Integer.parseInt(strSection);
                        }
                        String strPlanNum = urlResponse.queryResult("plan_num");
                        if (strPlanNum != null && !strPlanNum.isEmpty()) {
                            plan_num = Integer.parseInt(strPlanNum);
                        }
                        String strPlanIds = urlResponse.queryResult("plan_id");
                        if (strPlanIds != null && !strPlanIds.isEmpty()) {
                            Gson gson = new Gson();
                            listPlanId = gson.fromJson(strPlanIds, new TypeToken<List<String>>(){}.getType());
                        }
                        signHistory.setIsUpload(1);
                        signCallBack.onSignToday(true, urlResponse.getCode(), urlResponse.getMessage(), section, plan_num, listPlanId);
                    }else {
                        signCallBack.onSignToday(false, urlResponse.getCode(), urlResponse.getMessage(), 0, 0, null);
                    }
                }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                signCallBack.onSignToday(false, error.networkResponse.statusCode, errString, 0, 0, null);
            }else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                signCallBack.onSignToday(false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, 0, 0, null);
            }
        }){
            /*@Override
            protected Map<String, String> getParams(){
                //参数拼装:表单提交方式
                Map<String, String> params = new HashMap<>();
                params.put("sign_type", signHistory.getSignType() + "");
                int planmode = signHistory.getCarmode();
                if (planmode == 1)
                    params.put("plan_mode", planmode + "");
                params.put(("signAddress"), signHistory.getSignAddr());
                params.put(("locationX"), signHistory.getLng());
                params.put("locationY", signHistory.getLat());
                params.put("flag", signHistory.getGpsFlag() + "");
                if (deviceInfo != null){
                    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                    String strInfo = gson.toJson(deviceInfo);
                    if (strInfo != null && !strInfo.isEmpty()){
                        params.put("device", strInfo);
                    }
                }else {
                    params.put("device", "");
                }
                if (localPlanIds != null && localPlanIds.size() > 0){
                    Gson gson = new Gson();
                    String strPlanIds = gson.toJson(localPlanIds);
                    params.put("list", strPlanIds);
                }
                String app_ver_name = BaseApp.getAppVersionName();
                params.put("software_ver", app_ver_name);
                return params;
            }*/

            @Override
            public byte[] getBody() {
                JsonObject root = new JsonObject();
                root.addProperty("signType", signHistory.getSignType());
                int planmode = signHistory.getCarmode();
                if (planmode == 1)
                    root.addProperty("plan_mode", planmode + "");
                root.addProperty(("signAddress"), signHistory.getSignAddr());
                root.addProperty(("locationX"), signHistory.getLng());
                root.addProperty("locationY", signHistory.getLat());
                root.addProperty("flag", signHistory.getGpsFlag() + "");
                if (deviceInfo != null){
                    Gson gsonDevice = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                    String strInfo = gsonDevice.toJson(deviceInfo);
                    if (strInfo != null && !strInfo.isEmpty()){
                        //root.addProperty("decice", strInfo);
                        JsonObject device = new JsonParser().parse(strInfo).getAsJsonObject();
                        root.add("device", device);
                    }
                }else {
                    root.addProperty("device", "");
                }
                if (localPlanIds != null && localPlanIds.size() > 0){
                    String strPlanIds = StringUtil.listToString(localPlanIds, ',');;
                    root.addProperty("list", strPlanIds);
                }

                Gson gson = new Gson();
                String addSign = gson.toJson(root);
                return addSign.getBytes();
            }

            @Override
            public String getBodyContentType() {
                return JsonRequestConstant.PROTOCOL_CONTENT_TYPE;
            }

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

    @Override
    public void getDailyPlanAttened(Context context, String userid, final String date, final SignCallBack signCallBack) {
        String url = newApi_dyrq.getDailyAttendedUrl() + "?month=" + date + "&userId=" + 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.getResult();
                        int resCode = -1;
                        boolean result = false;
                        List<SignAttendedDataBean> attendedList = null;
                        String parseErrMsg = "用户解析失败";
                        if (rowsArray != null){
                            try {
                                Gson gson = new Gson();
                                List<SignAttendedDataBean> attendeds = gson.fromJson(rowsArray, new TypeToken<List<SignAttendedDataBean>>(){}.getType());
                                if (attendeds != null && attendeds.size() >= 0){
                                    attendedList = attendeds;
                                    resCode = responseCode.getCode();
                                    parseErrMsg = responseCode.getMessage();
                                    result = true;
                                }
                            }catch (Exception e){
                                signCallBack.onGetDailyPlanAttened(false, resCode, parseErrMsg, null);
                            }
                        }
                        signCallBack.onGetDailyPlanAttened(result, resCode, parseErrMsg, attendedList);
                    }else {
                        signCallBack.onGetDailyPlanAttened(
                                false, responseCode.getCode(), responseCode.getMessage(), null);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //登录失败
                if (error.networkResponse != null) {
                    String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                    signCallBack.onGetDailyPlanAttened(
                            false, error.networkResponse.statusCode, errString, null);
                }else {
                    String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                    signCallBack.onGetDailyPlanAttened(
                            false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null);
                }
            }
        }){
            @Override
            public Map<String, String> getHeaders(){
                //参数拼装:表单提交方式
                return newApi_dyrq.getHeaderParams();
            }
        };
        BaseApp.addRequest(context.getClass().getName(), postRequest,
                BaseApp.UPLOAD_FILE_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 0);
    }

    private void saveSignListToday(String userid, List<SignHistoryDataBean> signDataBeans){
        if (signDataBeans != null){
            for (SignHistoryDataBean signDataBean : signDataBeans){
                int status = signDataBean.getSignType();
                String sign_time = signDataBean.getSignTime();
                SignHistoryDataBean historyDataBean = dbDaoHelper.getSignHistoryToday(userid, sign_time, status);
                if (historyDataBean == null) {
                    signDataBean.setIsUpload(1);
                    dbDaoHelper.saveSignHistoryData(signDataBean);
                }
            }
        }
    }
}
