package com.tofly.ghrq_route.module.job.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;
import com.tofly.ghrq_route.module.job.JobDaoHelper;
import com.tofly.ghrq_route.module.job.JobTool;
import com.tofly.ghrq_route.module.job.NotifyMsgDaoHelper;
import com.tofly.ghrq_route.module.job.controller.JobCallBack;
import com.tofly.ghrq_route.module.job.domain.JobBean;
import com.tofly.ghrq_route.module.notifyManage.NotifyManageBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.MimeUtil;
import com.tofly.ghrq_route.common.util.net.volley.MultiPartStringRequest;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class JobServiceImpl implements IJobService {
    private JobDaoHelper jobDaoHelper;
    private NotifyMsgDaoHelper notifyMsgDaoHelper;

    public JobServiceImpl() {
        jobDaoHelper = JobDaoHelper.getInstance();
        notifyMsgDaoHelper = NotifyMsgDaoHelper.getInstance();
    }

    @Override
    public void getJobList(Context context, int job_state, int pageindex, int pagesize, JobCallBack jobCallBack) {
        String url = newApi_dyrq.getJobListUrl() + "?current=" + pageindex + "&size=" + pagesize
                + "&orders[0].asc=false&orders[0].column=DISPATCH_DATE";
        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<JobBean> jobList = 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<JobBean> jobBeans = gson.fromJson(rowsArray, new TypeToken<List<JobBean>>(){}.getType());
                                if (jobBeans != null) {
                                    jobList = jobBeans;
                                    resCode = responseCode.getCode();
                                    parseErrMsg = responseCode.getMessage();
                                    result = true;

                                    saveJobList(jobList);
                                }
                            } catch (Exception e) {
                                parseErrMsg = "用户解析失败";
                                jobCallBack.onGetJobList(false, resCode, parseErrMsg, null, 0);
                            }
                        }
                        jobCallBack.onGetJobList(result, resCode, parseErrMsg, jobList, total);
                    } else {
                        jobCallBack.onGetJobList(
                                false, responseCode.getCode(), responseCode.getMessage(), null, 0);
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        jobCallBack.onGetJobList(
                                false, error.networkResponse.statusCode, errString, null, 0);
                    } else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        jobCallBack.onGetJobList(
                                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 jobBeans 服务器上获取的工单
     * */
    private void saveJobList(List<JobBean> jobBeans) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (jobBeans != null && userBean != null) {
            String userid = userBean.getUserid();
            jobDaoHelper.deleteJobBeans(userid, JobBean.JOB_TASK_STATUS.JOB_TASK_UNHANDLED.getStatus());
            jobDaoHelper.deleteJobBeans(userid, JobBean.JOB_TASK_STATUS.JOB_TASK_COMMITED.getStatus());
            for (JobBean jobBean : jobBeans) {
                JobBean localJobBean = jobDaoHelper.getJobBean(jobBean.getId());
                if (localJobBean == null) {
                    jobBean.setUserid(userid);
                    jobDaoHelper.insertJobBean(jobBean);
                }else {
                    /*服务器已经处理完的工单以服务器数据为主，删除本地的工单数据和图片*/
                    boolean isServerFinished = jobBean.getTaskStatus() == JobBean.JOB_TASK_STATUS.JOB_TASK_COMMITED.getStatus();
                    boolean isLocalUnCommitted = localJobBean.getTaskStatus() == JobBean.JOB_TASK_STATUS.JOB_TASK_UNCOMMIT.getStatus();
                    if (isServerFinished && isLocalUnCommitted) {
                        JobTool jobTool = JobTool.getInstance();
                        jobTool.deleteLocalJobData(jobBean);
                        jobDaoHelper.insertJobBean(jobBean);
                    }
                }
            }
        }
    }

    @Override
    public void uploadJobData(Context context, JobBean jobBean, List<TroublePictureBean> photos, JobCallBack jobCallBack) {
        String url = newApi_dyrq.getJobHandleUrl();
        MultiPartStringRequest postRequest = new MultiPartStringRequest(Request.Method.POST,
                url, response -> {
                    URLResponseCode.URLResponse responseCode = new URLResponseCode.URLResponse(response);
                    if (responseCode.getCode() == URLResponseCode.ErrorCode.SUCCESS){
                        jobCallBack.onUploadJobData(true, responseCode.getCode(), responseCode.getMessage());
                    }else {
                        jobCallBack.onUploadJobData(false, responseCode.getCode(), responseCode.getMessage());
                    }
                }, error -> {
                    //登录失败
                    if (error.networkResponse != null) {
                        String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                        jobCallBack.onUploadJobData(false, error.networkResponse.statusCode, errString);
                    }else {
                        String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                        jobCallBack.onUploadJobData(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("taskid", jobBean.getId());
                params.put("handleRecord", jobBean.getHandleRecord());
                params.put("finishDate", jobBean.getFinishDate());
                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 = "file" + count + "," + 0 + "," + time;*/
                        String key = "file" + count ;
                        if (file != null && !file.isEmpty())
                            params.put(key, new File(file));
                    }
                }
                return params;
            }
        };
        BaseApp.addMultiStatckRequest(context.getClass().getName(), postRequest);
    }

    @Override
    public void getJobData(Context context, String job_id, JobCallBack jobCallBack) {
        String url = newApi_dyrq.getJobDataUrl() + job_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");
                JobBean jobBean = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                if (rowsArray != null) {
                    try {
                        Gson gson = new Gson();
                        JobBean job = gson.fromJson(rowsArray, new TypeToken<JobBean>(){}.getType());
                        if (job != null) {
                            jobBean = job;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;

                            /*保存工单详情*/
                            saveJobData(jobBean);

                            if (fileids != null && !fileids.isEmpty()) {
                                List<String> files = gson.fromJson(fileids, new TypeToken<List<String>>(){}.getType());
                                if (files != null) {
                                    /*保存工单图片*/
                                    saveJobPictures(jobBean.getId(), files);
                                }
                            }
                        }
                    } catch (Exception e) {
                        jobCallBack.onGetJobData(false, resCode, parseErrMsg, null);
                    }
                }
                jobCallBack.onGetJobData(result, resCode, parseErrMsg, jobBean);
            } else {
                jobCallBack.onGetJobData(
                        false, responseCode.getCode(), responseCode.getMessage(), null);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                jobCallBack.onGetJobData(
                        false, error.networkResponse.statusCode, errString, null);
            } else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                jobCallBack.onGetJobData(
                        false, URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT, errString, null);
            }
        }) {

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

    /**
     * 保存从服务器上获取的工单详情
     * @param jobBean 服务器上获取的工单
     * */
    private void saveJobData(JobBean jobBean) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (jobBean != null && userBean != null) {
            String userid = userBean.getUserid();
            jobBean.setUserid(userid);
            jobDaoHelper.insertOrUpdateJobBean(jobBean);
        }
    }

    /**
     * 保存从服务器上获取的工单图片，先删除本地的图片(不包括未提交的工单)
     * @param jobPictures 服务器上获取的图片
     * */
    private void saveJobPictures(String job_id, List<String> jobPictures) {
        if (jobPictures != null) {
            jobDaoHelper.deleteSavedJobPictures(job_id);
            for (String fileUrl : jobPictures) {
                if (fileUrl != null && !fileUrl.isEmpty()) {
                    TroublePictureBean pictureBean = new TroublePictureBean();
                    String pictureid = UUID.randomUUID().toString();
                    String filetype = MimeUtil.getMimeType(fileUrl);
                    String time = DateUtils.getDate(new Date().getTime());
                    pictureBean.setId(pictureid);
                    pictureBean.setTroubleid(job_id);
                    pictureBean.setFileurl(fileUrl);
                    pictureBean.setFiletype(filetype);
                    pictureBean.setStatus(TroubleBean.SERVER_STATE);
                    pictureBean.setCreateTime(time);
                    jobDaoHelper.insertOrUpdateJobPicture(pictureBean);
                }
            }
        }
    }

    @Override
    public void getUnHandledJobCount(Context context, JobCallBack jobCallBack) {
        String url = newApi_dyrq.getJobUnhandledUrl();
        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("taskids");
                List<String> jobIdList = null;
                int resCode = -1;
                boolean result = false;
                String parseErrMsg = "用户解析失败";
                String strTotal = responseCode.queryResult("total");
                int total = 0;
                if (strTotal != null && !strTotal.isEmpty()) {
                    total = Integer.parseInt(strTotal);
                }
                if (rowsArray != null) {
                    try {
                        Gson gson = new Gson();
                        List<String> jobIds = gson.fromJson(rowsArray, new TypeToken<List<String>>(){}.getType());
                        if (jobIds != null) {
                            jobIdList = jobIds;
                            resCode = responseCode.getCode();
                            parseErrMsg = responseCode.getMessage();
                            result = true;

                            /*保存未读工单个数*/
                            saveUnhandedJobData(jobIdList);
                        }
                    } catch (Exception e) {
                        jobCallBack.onGetUnHandledJobCount(false, resCode, parseErrMsg, jobIdList, 0);
                    }
                }
                jobCallBack.onGetUnHandledJobCount(result, resCode, parseErrMsg, jobIdList, total);
            } else {
                jobCallBack.onGetUnHandledJobCount(
                        false, responseCode.getCode(), responseCode.getMessage(), null, 0);
            }
        }, error -> {
            //登录失败
            if (error.networkResponse != null) {
                String errString = new String(error.networkResponse.data, StandardCharsets.UTF_8);
                jobCallBack.onGetUnHandledJobCount(
                        false, error.networkResponse.statusCode, errString, null, 0);
            } else {
                String errString = URLResponseCode.ErrorCode.getErrorMessage(URLResponseCode.ErrorCode.HTTPCONN_TIMEOUT);
                jobCallBack.onGetUnHandledJobCount(
                        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 jobIds 服务器上获取的未处理的工单id和个数
     * */

    private void saveUnhandedJobData(List<String> jobIds) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (jobIds != null && userBean != null) {
            for (String jobid : jobIds) {
                NotifyManageBean notifyManageBean = notifyMsgDaoHelper.getJobNotifyMsgBean(userBean.getUserid(), jobid);
                if (notifyManageBean == null) {
                    notifyManageBean = new NotifyManageBean();
                    String id = UUID.randomUUID().toString();
                    notifyManageBean.setId(id);
                    notifyManageBean.setServerId(jobid);
                    notifyManageBean.setNotify_type(NotifyManageBean.NOTIFY_MSG_TYPE.NOTIFY_MSG_JOB.getType());
                    notifyManageBean.setIsNotify(false);
                    notifyManageBean.setIsRead(false);
                    notifyManageBean.setUserid(userBean.getUserid());
                    notifyMsgDaoHelper.insertNotifyMsgBean(notifyManageBean);
                }
            }
        }
    }
}
