package com.tofly.ghrq_route.module.sketch;

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.module.OfflineWork.OfflineWorkTool;
import com.tofly.ghrq_route.module.OfflineWork.domain.OfflineWorkJobBean;
import com.tofly.ghrq_route.module.sketch.controller.SketchCallback;
import com.tofly.ghrq_route.module.sketch.controller.SketchController;
import com.tofly.ghrq_route.module.sketch.domain.SketchBean;
import com.tofly.ghrq_route.module.sketch.domain.SketchBean.SKETCH_TASK_STATUS;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.file.FileUtil;

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

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

    private static SketchTool sketchTool = null;

    private OfflineWorkTool offlineWorkTool;

    private SketchController sketchController;

    private SketchDaoHelper sketchDaoHelper;

    private SketchTool() {
        sketchDaoHelper = SketchDaoHelper.getInstance();
        offlineWorkTool = OfflineWorkTool.getInstance();
    }

    public static synchronized SketchTool getInstance() {
        if (sketchTool == null) {
            sketchTool = new SketchTool();
        }
        return sketchTool;
    }

    /**
     * 从服务器获取草图列表
     * */
    public void getSketchListOnline(Context context, SketchCallback sketchCallback){
        int sketch_state = 0;
        getSketchList(context, sketch_state, true, sketchCallback);
    }

    /**
     * 从本地获取草图列表
     * @param sketch_state  工单的状态：0: 未提交 1：已提交
     * */
    public void getSketchListOffline(final Context context, int sketch_state, SketchCallback sketchCallback){
        getSketchList(context, sketch_state, false, sketchCallback);
    }

    /**
     * 从服务器/本地获取草图列表
     * @param sketch_state  工单的状态：0: 未提交 1：已提交
     * */
    private void getSketchList(final Context context, int sketch_state, boolean online, final SketchCallback sketchCallback) {
        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 (sketchController == null)
                sketchController = new SketchController();
            sketchController.getSketchList(context, userBean.getUserid(), sketch_state, pageindex, pagesize, online, new SketchCallback() {
                @Override
                public void onGetSketchList(boolean isSuccess, int errorCode, String errMsg, List<SketchBean> sketchList, int total) {
                    super.onGetSketchList(isSuccess, errorCode, errMsg, sketchList, total);
                    //ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getString(R.string.sketch_list_get_list_error) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (sketchCallback != null)
                        sketchCallback.onGetSketchList(isSuccess, errorCode, errMsg, sketchList, total);
                }
            });
        }
    }

    /**
     * 读取本地草图信息
     * @param sketch_id 草图的id
     * */
    public SketchBean getLocalSketchBean(String sketch_id){ return sketchDaoHelper.getSketchBean(sketch_id); }

    /**
     * 保存草图不自动提交，需手动提交
     * */
    public void saveSketchDataNoCommit(SketchBean sketchBean) {
        saveSketchData(sketchBean, false);
    }

    /**
     * 保存草图数据
     * */
    private void saveSketchData(SketchBean sketchBean, boolean auto_commit) {
        if (sketchBean != null) {
            /*保存隐患的数据信息*/
            String sketch_id = sketchBean.getId();
            if (sketch_id.isEmpty()){
                sketch_id = UUID.randomUUID().toString();
                sketchBean.setId(sketch_id);
            }

            int save_state = auto_commit ? TroubleBean.SAVED_STATE : TroubleBean.SAVED_NO_COMMIT_STATE;
            sketchBean.setCommit_status(save_state);
            sketchBean.setStatus(SKETCH_TASK_STATUS.SKETCH_TASK_UNCOMMIT.getStatus());
            if (sketchBean.getUserid() == null || sketchBean.getUserid().isEmpty()) {
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                if (userBean != null)
                    sketchBean.setUserid(userBean.getUserid());
            }
            sketchDaoHelper.insertOrUpdateSketchBean(sketchBean);

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

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

    /**
     * 删除草图数据
     * */
    public void deleteSketchData(SketchBean sketchBean) {
        if (sketchBean != null) {
            String sketch_id = sketchBean.getId();
            sketchDaoHelper.deleteSketchBean(sketch_id);

            /*删除离线上传任务，如果存在*/
            offlineWorkTool.deleteOfflineWorkJob(sketch_id);

            String filepath = sketchBean.getFilepath();
            if (filepath != null && FileUtil.fileExists(filepath)) {
                FileUtil.deleteFile(filepath);
            }
        }
    }

    private void updateLocalPhotoAudio(SketchBean sketchBean){
        if (sketchBean.getId() != null && sketchBean.getId().isEmpty()) {
            /*删除本地的离线上传任务*/
            offlineWorkTool.deleteOfflineWorkJob(sketchBean.getId());
        }

/*        sketchBean.setStatus(SKETCH_TASK_STATUS.SKETCH_TASK_COMMITED.getStatus());
        sketchBean.setCommit_status(TroubleBean.UPLOADED_STATE);*/
        sketchDaoHelper.deleteSketchBean(sketchBean.getId());

        /*删除本地草图的图片*/
        String filepath = sketchBean.getFilepath();
        if (filepath != null && FileUtil.fileExists(filepath)) {
            FileUtil.deleteFile(filepath);
        }
    }

    private void saveSketchCommitState(SketchBean sketchBean, int commit_state){
        if (sketchBean != null) {
            sketchBean.setCommit_status(commit_state);
            sketchDaoHelper.insertOrUpdateSketchBean(sketchBean);
        }
    }

    public void uploadSketchData(final Context context, final SketchBean sketchBean, SketchCallback sketchCallback){
        uploadSketchData(context, sketchBean, true, sketchCallback);
    }

    public void uploadSketchDataNoSave(final Context context, final SketchBean sketchBean, SketchCallback sketchCallback){
        uploadSketchData(context, sketchBean, false, sketchCallback);
    }

    private void uploadSketchData(final Context context, final SketchBean sketchBean,
                                  final boolean saveOnFail, final SketchCallback sketchCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && sketchBean != null) {
            final int old_commit_state = sketchBean.getCommit_status();
            saveSketchCommitState(sketchBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (sketchController == null)
                sketchController = new SketchController();
            sketchController.uploadSketchData(context, sketchBean, new SketchCallback() {
                @Override
                public void onUploadSketchData(boolean isSuccess, int errorCode, String errMsg) {
                    super.onUploadSketchData(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        String strWarn = context.getString(R.string.sketch_sketch_upload_ok);
                        ToastUtil.showToast(context, strWarn);

                        updateLocalPhotoAudio(sketchBean);
                    } else {
                        if (saveOnFail)
                            saveSketchData(sketchBean, false);
                        else {
                            saveSketchCommitState(sketchBean, old_commit_state);
                        }

                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getString(R.string.dangerreport_next_upload_error) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (sketchCallback != null){
                        sketchCallback.onUploadSketchData(isSuccess, errorCode, errMsg);
                    }
                }
            });
        }
    }

    /**
     * 从服务器获取草图详情
     * @param sketch_id  草图的id
     * */
    public void getSketchDataFromServer(Context context, String sketch_id, final SketchCallback sketchCallback){
        getSketchData(context, sketch_id, true, sketchCallback);
    }

    /**
     * 从本地获取草图详情
     * @param sketch_id  草图的id
     * */
    private void getSketchDataFromLocal(Context context, String sketch_id, final SketchCallback sketchCallback){
        getSketchData(context, sketch_id, false, sketchCallback);
    }

    /**
     * 从服务器获取草图详情, 读取失败后从本地获取
     * @param sketch_id  草图的id
     * */
    public void getSketchData(final Context context, final String sketch_id, final SketchCallback sketchCallback){
        getSketchDataFromServer(context, sketch_id, new SketchCallback(){
            @Override
            public void onGetSketchData(boolean isSuccess, int errorCode, String errMsg, SketchBean sketchBean) {
                super.onGetSketchData(isSuccess, errorCode, errMsg, sketchBean);
                if (isSuccess){
                    sketchCallback.onGetSketchData(true, errorCode, errMsg, sketchBean);
                }else {
                    getSketchDataFromLocal(context, sketch_id, sketchCallback);
                }
            }
        });
    }

    /**
     * 从服务器/本地获取草图详情
     * @param sketch_id  草图的id
     * */
    private void getSketchData(final Context context, String sketch_id, boolean online, final SketchCallback sketchCallback) {
        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 (sketchController == null)
                sketchController = new SketchController();
            sketchController.getSketchData(context, sketch_id, online, new SketchCallback() {
                @Override
                public void onGetSketchData(boolean isSuccess, int errorCode, String errMsg, SketchBean sketchBean) {
                    super.onGetSketchData(isSuccess, errorCode, errMsg, sketchBean);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getString(R.string.sketch_get_data_error) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (sketchCallback != null)
                        sketchCallback.onGetSketchData(isSuccess, errorCode, errMsg, sketchBean);
                }
            });
        }
    }
}
