package com.tofly.ghrq_route.module.job;

import android.content.Context;

import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.module.OfflineWork.OfflineWorkTool;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineWorkJobBean;
import com.tofly.ghrq_route.module.job.controller.JobCallBack;
import com.tofly.ghrq_route.module.job.controller.JobController;
import com.tofly.ghrq_route.module.job.domain.JobBean;
import com.tofly.ghrq_route.module.job.domain.JobBean.JOB_TASK_STATUS;
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.file.FileUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class JobTool {
    private static final String TAG = JobTool.class.getName();

    private static JobTool jobTool = null;

    private OfflineWorkTool offlineWorkTool;

    private JobController jobController;

    private JobDaoHelper jobDaoHelper;

    private NotifyMsgDaoHelper notifyMsgDaoHelper;

    private JobTool() {
        jobDaoHelper = JobDaoHelper.getInstance();
        notifyMsgDaoHelper = NotifyMsgDaoHelper.getInstance();
        offlineWorkTool = OfflineWorkTool.getInstance();
    }

    public static synchronized JobTool getInstance() {
        if (jobTool == null) {
            jobTool = new JobTool();
        }
        return jobTool;
    }

    /**
     * 从服务器获取工单列表
     * */
    public void getJobListOnline(Context context, JobCallBack jobCallBack){
        int job_state = 0;
        getJobList(context, job_state, true, jobCallBack);
    }

    /**
     * 从本地获取工单列表
     * @param job_state  工单的状态：0: 未完成 1：未提交 2：已完成
     * */
    public void getJobListOffline(final Context context, int job_state, JobCallBack jobCallBack){
        getJobList(context, job_state, false, jobCallBack);
    }

    /**
     * 从服务器/本地获取工单列表
     * @param job_state  工单的状态：0: 未完成 1：未提交 2：已完成
     * */
    private void getJobList(final Context context, int job_state, boolean online, final JobCallBack jobCallBack) {
        final int pageindex = 1;
        final int pagesize = C.DEFAULT_MAX_LOAD_PAGESIZE;
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            //String strUploading = context.getResources().getString(R.string.updating_data);
            //ProgressManager.getInstance().showProgress(context, null, strUploading, false);
            if (jobController == null)
                jobController = new JobController();
            jobController.getJobList(context, job_state, pageindex, pagesize, online, new JobCallBack() {
                @Override
                public void onGetJobList(boolean isSuccess, int errorCode, String errMsg, List<JobBean> jobList, int total) {
                    super.onGetJobList(isSuccess, errorCode, errMsg, jobList, total);
                    //ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getString(R.string.job_list_get_list_error) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (jobCallBack != null)
                        jobCallBack.onGetJobList(isSuccess, errorCode, errMsg, jobList, total);
                }
            });
        }
    }

    /**
     * 读取本地工单信息
     * @param job_id 工单的id
     * */
    public JobBean getLocalJobBean(String job_id){
        return jobDaoHelper.getJobBean(job_id);
    }

    /**
     * 保存工单不自动提交，需手动提交
     * */
    public void saveJobDataNoCommit(JobBean jobBean, List<TroublePictureBean> pictureBeans) {
        saveJobData(jobBean, pictureBeans, false);
    }

    /**
     * 保存工单数据
     * */
    private void saveJobData(JobBean jobBean, List<TroublePictureBean> pictureBeans, boolean auto_commit) {
        if (jobBean != null) {
            /*保存隐患的数据信息*/
            String jobId = jobBean.getId();
            if (jobId.isEmpty()){
                jobId = UUID.randomUUID().toString();
                jobBean.setId(jobId);
            }


            int save_state = auto_commit ? TroubleBean.SAVED_STATE : TroubleBean.SAVED_NO_COMMIT_STATE;
            jobBean.setCommit_status(save_state);
            jobBean.setTaskStatus(JOB_TASK_STATUS.JOB_TASK_UNCOMMIT.getStatus());
            if (jobBean.getUserid() == null || jobBean.getUserid().isEmpty()) {
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                if (userBean != null)
                    jobBean.setUserid(userBean.getUserid());
            }
            jobDaoHelper.insertOrUpdateJobBean(jobBean);

            /*创建新的离线上传任务*/
            OfflineWorkJobBean workJobBean = offlineWorkTool.newOfflineWorkJob(jobId,
                    OfflineWorkJobBean.OfflineWorkJobType.JOB_MY_JOB_ADD);

            /*保存工单的图片*/
            if (pictureBeans != null && pictureBeans.size() > 0) {
                List<String> pic_ids = new ArrayList<>();
                for (TroublePictureBean pictureBean : pictureBeans) {
                    if (pictureBean != null && FileUtil.fileExists(pictureBean.getFilepath())) {
                        pictureBean.setTroubleid(jobId);
                        pictureBean.setStatus(save_state);
                        jobDaoHelper.insertOrUpdateJobPicture(pictureBean);

                        pic_ids.add(pictureBean.getId());
                    }
                }
                workJobBean.setRef_photo_ids(pic_ids);
            }

            if (auto_commit)
                offlineWorkTool.insertOfflineWorkJob(workJobBean);
        }
    }

    private void updateLocalPhotoAudio(JobBean jobBean, List<TroublePictureBean> pictureBeans){
        if (jobBean.getId() != null && jobBean.getId().isEmpty()) {
            /*删除本地的离线上传任务*/
            OfflineWorkJobBean workJobBean = offlineWorkTool.getOfflineWorkJob(jobBean.getId());
            if (workJobBean != null){
                offlineWorkTool.deleteOfflineWorkJob(workJobBean);
            }
        }

        jobBean.setTaskStatus(JOB_TASK_STATUS.JOB_TASK_COMMITED.getStatus());
        jobBean.setCommit_status(TroubleBean.UPLOADED_STATE);
        jobDaoHelper.insertOrUpdateJobBean(jobBean);

        /*更新本地隐患的图片*/
        for (TroublePictureBean pictureBean : pictureBeans) {
            if (pictureBean != null) {
                if (FileUtil.fileExists(pictureBean.getFilepath())) {
                    pictureBean.setTroubleid(jobBean.getId());
                    pictureBean.setStatus(TroubleBean.UPLOADED_STATE);
                    jobDaoHelper.insertOrUpdateJobPicture(pictureBean);
                }else {
                    jobDaoHelper.deleteSavedJobPicture(pictureBean);
                }
            }
        }
    }

    public void deleteLocalJobData(JobBean jobBean){
        if (jobBean.getId() != null && jobBean.getId().isEmpty()) {
            /*删除本地的离线上传任务*/
            OfflineWorkJobBean workJobBean = offlineWorkTool.getOfflineWorkJob(jobBean.getId());
            if (workJobBean != null){
                offlineWorkTool.deleteOfflineWorkJob(workJobBean);
            }

            jobDaoHelper.deleteJobBean(jobBean);

            List<TroublePictureBean> pictureBeans = jobDaoHelper.getSavedJobPicture(jobBean.getId());
            if (pictureBeans != null) {
                /*删除本地工单的图片*/
                for (TroublePictureBean pictureBean : pictureBeans) {
                    if (pictureBean != null) {
                        jobDaoHelper.deleteSavedJobPicture(pictureBean);
                        FileUtil.deleteFile(pictureBean.getFilepath());
                    }
                }
            }
        }
    }

    private void saveJobCommitState(JobBean jobBean, int commit_state){
        if (jobBean != null) {
            jobBean.setCommit_status(commit_state);
            jobDaoHelper.insertOrUpdateJobBean(jobBean);
        }
    }

    public void uploadJobData(final Context context, final JobBean jobBean,
                              final List<TroublePictureBean> photos, JobCallBack jobCallBack){
        uploadJobData(context, jobBean, photos, true, jobCallBack);
    }

    public void uploadJobDataNoSave(final Context context, final JobBean jobBean,
                              final List<TroublePictureBean> photos, JobCallBack jobCallBack){
        uploadJobData(context, jobBean, photos, false, jobCallBack);
    }

    private void uploadJobData(final Context context, final JobBean jobBean, final List<TroublePictureBean> photos,
                                  final boolean saveOnFail, final JobCallBack jobCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && jobBean != null) {
            final int old_commit_state = jobBean.getCommit_status();
            saveJobCommitState(jobBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (jobController == null)
                jobController = new JobController();
            jobController.uploadJobData(context, jobBean, photos, new JobCallBack() {
                @Override
                public void onUploadJobData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadJobData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        String strWarn = context.getString(R.string.job_job_upload_ok);
                        ToastUtil.showToast(context, strWarn);

                        updateLocalPhotoAudio(jobBean, photos);
                    } else {
                        if (errorCode == URLResponseCode.ErrorCode.ALREADY_EXISTS) {  //工单已完成
                            deleteLocalJobData(jobBean);
                            String strWarn = context.getString(R.string.job_job_finished_no_commit);
                            ToastUtil.showToast(context, strWarn);
                        }else {
                            if (saveOnFail)
                                saveJobData(jobBean, photos, false);
                            else {
                                saveJobCommitState(jobBean, old_commit_state);
                            }
                        }
                    }

                    if (jobCallBack != null){
                        jobCallBack.onUploadJobData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    /**
     * 读取本地工单图片
     * @param job_id 工单的id
     * */
    public List<TroublePictureBean> getLocalJobPictures(String job_id){
        return jobDaoHelper.getSavedJobPicture(job_id);
    }

    public void deleteLocalJobPicture(TroublePictureBean pictureBean) {
        jobDaoHelper.deleteSavedJobPicture(pictureBean);
    }

    public void deleteLocalJobPictures(List<TroublePictureBean> pictureBeans) {
        jobDaoHelper.deleteSavedJobPictures(pictureBeans);
    }

    public void deleteLocalJobPictures(String job_id) {
        jobDaoHelper.deleteSavedJobPictures(job_id);
    }

    /**
     * 从服务器获取工单详情
     * @param job_id  工单的id
     * */
    public void getJobDataFromServer(Context context, String job_id, final JobCallBack jobCallBack){
        getJobData(context, job_id, true, jobCallBack);
    }

    /**
     * 从本地获取工单详情
     * @param job_id  工单的id
     * */
    private void getJobDataFromLocal(Context context, String job_id, final JobCallBack jobCallBack){
        getJobData(context, job_id, false, jobCallBack);
    }

    /**
     * 从服务器获取工单详情, 读取失败后从本地获取
     * @param job_id  工单的id
     * */
    public void getJobData(final Context context, final String job_id, final JobCallBack jobCallBack){
        getJobDataFromServer(context, job_id, new JobCallBack(){
            @Override
            public void onGetJobData(boolean isSuccess, int errorCode, String errMsg, JobBean jobBean) {
                super.onGetJobData(isSuccess, errorCode, errMsg, jobBean);
                if (isSuccess){
                    jobCallBack.onGetJobData(true, errorCode, errMsg, jobBean);
                }else {
                    getJobDataFromLocal(context, job_id, jobCallBack);
                }
            }
        });
    }

    /**
     * 从服务器/本地获取工单详情
     * @param job_id  工单的id
     * */
    private void getJobData(final Context context, String job_id, boolean online, final JobCallBack jobCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            String strUploading = context.getResources().getString(R.string.updating_data);
            ProgressManager.getInstance().showProgress(context, null, strUploading, false);
            if (jobController == null)
                jobController = new JobController();
            jobController.getJobData(context, job_id, online, new JobCallBack() {
                @Override
                public void onGetJobData(boolean isSuccess, int errorCode, String errMsg, JobBean jobBean) {
                    super.onGetJobData(isSuccess, errorCode, errMsg, jobBean);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getString(R.string.job_job_get_data_error) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (jobCallBack != null)
                        jobCallBack.onGetJobData(isSuccess, errorCode, errMsg, jobBean);
                }
            });
        }
    }

    public void getServerUnhandledJob(final Context context, final JobCallBack jobCallBack) {
        getUnhandledJob(context, true, jobCallBack);
    }

    /**
     * 从服务器/本地获取未处理工单个数，id
     * */
    private void getUnhandledJob(final Context context, boolean online, final JobCallBack jobCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            if (jobController == null)
                jobController = new JobController();
            jobController.getUnHandledJob(context, online, new JobCallBack() {
                @Override
                public void onGetUnHandledJobCount(boolean isSuccess, int errorCode, String errMsg, List<String> jobIds, int total) {
                    super.onGetUnHandledJobCount(isSuccess, errorCode, errMsg, jobIds, total);

                    if (jobCallBack != null)
                        jobCallBack.onGetUnHandledJobCount(isSuccess, errorCode, errMsg, jobIds, total);
                }
            });
        }
    }

    public NotifyManageBean getNotifyMsgBean(String job_id) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            return notifyMsgDaoHelper.getJobNotifyMsgBean(userBean.getUserid(), job_id);
        }
        return null;
    }

    public List<NotifyManageBean> getUnNotifyMsgBean() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            return notifyMsgDaoHelper.getJobUnNotifyMsgBean(userBean.getUserid());
        }
        return null;
    }

    public void setMsgBeanNotified(List<NotifyManageBean> msgBeans) {
        if (msgBeans != null) {
            for (NotifyManageBean msgBean : msgBeans) {
                msgBean.setIsNotify(true);
            }
            notifyMsgDaoHelper.upadteNotifyMsgBeans(msgBeans);
        }
    }

    public void setMsgBeanRead(NotifyManageBean msgBean) {
        if (msgBean != null) {
            msgBean.setIsRead(true);
            notifyMsgDaoHelper.upadteNotifyMsgBean(msgBean);
        }
    }
}
