package com.tofly.ghrq_route.module.rushrepair;

import android.content.Context;

import com.gaoyuan.weixinrecord.example.Record;
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.domain.OfflineWorkJobBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildFileBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.rushrepair.controller.RushRepairController;
import com.tofly.ghrq_route.module.rushrepair.controller.RushRepairCallback;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairBean;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairProcessBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
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 RushRepairTool {

    private static RushRepairTool buildJobTool = null;

    private DBDaoHelper dbDaoHelper;

    private RushRepairController rushRepairController;

    public RushRepairTool() {
        dbDaoHelper = DBDaoHelper.getInstance();
    }

    public static synchronized RushRepairTool getInstance() {
        if (buildJobTool == null) {
            buildJobTool = new RushRepairTool();
        }
        return buildJobTool;
    }

    public void addJobManage(Context context, RushRepairBean rushRepairBean, List<TroublePictureBean> photos,
                             List<Record> records, List<BuildFileBean> filesList, RushRepairCallback rushRepairCallback) {
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        if (filesList != null && filesList.size() > 0) {
            dbDaoHelper.saveBuildFiles(filesList, "2", rushRepairBean.getId());
        }
        addBuildJobManage(context, rushRepairBean, photos, audioBeans, filesList, true, rushRepairCallback);
    }

    /**
     * 新建抢维修工单上传
     */

    public void addBuildJobManage(final Context context, final RushRepairBean RushRepairBean, final List<TroublePictureBean> photos,
                                  final List<TroubleAudioBean> audios, final List<BuildFileBean> filesList, final boolean saveOnFail,
                                  final RushRepairCallback buildManageCallback) {
        if (RushRepairBean != null) {
            saveBuildJobManageInfo(RushRepairBean, BuildManageBean.BUILD_SUBMIT_ZERO);
            if (rushRepairController == null)
                rushRepairController = new RushRepairController(context);
            rushRepairController.addBuildJobManage(RushRepairBean, photos, audios, filesList, new RushRepairCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        deleteLocalBuildJobManage(RushRepairBean, photos, audios, filesList);
                    } else {
                        if (saveOnFail) {
                            saveBuildJobManageInfo(RushRepairBean, photos, audios, filesList);
                        } else {
                            saveBuildJobManageInfo(RushRepairBean, BuildManageBean.BUILD_SUBMIT_ONE);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getResources().getString(R.string.build_job_upload_info_err) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }
                    if (buildManageCallback != null)
                        buildManageCallback.onAddBuildManage(isSuccess, errorCode, errMsg);
                }
            });
        }
    }

    private void saveBuildJobManageInfo(RushRepairBean rushRepairBean, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> fileBeanList) {
        if (rushRepairBean != null) {
            OfflineWorkJobBean workJobBean1 = dbDaoHelper.getOfflineWorkJob(rushRepairBean.getId());
            if (workJobBean1 == null) {
                int save_state = BuildManageBean.BUILD_SUBMIT_ONE;
                OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
                String job_id = UUID.randomUUID().toString();
                workJobBean.setId(job_id);
                workJobBean.setJob_type(OfflineWorkJobBean.OfflineWorkJobType.JOB_RUSH_REPAIR_ADD);
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                workJobBean.setUser_id(userBean.getUserid());

                /*保存工单的数据信息*/
                rushRepairBean.setSubmit_state("" + save_state);
                dbDaoHelper.insertOrUpdateBuildJobManage(rushRepairBean);

                workJobBean.setRef_id(String.valueOf(rushRepairBean.getId()));

                /*保存隐患的图片*/
                if (pictures != null && pictures.size() > 0) {
                    List<String> pic_ids = new ArrayList<>();
                    for (TroublePictureBean pictureBean : pictures) {
                        if (pictureBean != null && FileUtil.fileExists(pictureBean.getFilepath())) {
                            pictureBean.setTroubleid(String.valueOf(rushRepairBean.getId()));
                            pictureBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateTroublePicture(pictureBean);

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

                /*保存隐患的音频*/
                String filetype = "amr";
                if (audios != null && audios.size() > 0) {
                    List<String> audio_ids = new ArrayList<>();
                    for (TroubleAudioBean audioBean : audios) {
                        if (audioBean != null && FileUtil.fileExists(audioBean.getPath())) {
                            String audioId = UUID.randomUUID().toString();
                            audioBean.setId(audioId);
                            audioBean.setTroubleid(String.valueOf(rushRepairBean.getId()));
                            audioBean.setFiletype(filetype);
                            audioBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateTroubleAudio(audioBean);

                            audio_ids.add(audioId);
                        }
                    }
                    workJobBean.setRef_audio_ids(audio_ids);
                }

                /*保存附件*/
                if (fileBeanList != null && fileBeanList.size() > 0) {
                    List<String> files_id = new ArrayList<>();
                    for (BuildFileBean buildFileBean : fileBeanList) {
                        if (buildFileBean != null && FileUtil.fileExists(buildFileBean.getFilePath())) {
                            buildFileBean.setRepairId(rushRepairBean.getId());
                            buildFileBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateBuildFiles(buildFileBean);
                            files_id.add(buildFileBean.getId());
                        }
                    }
                    workJobBean.setRef_data_ids(files_id);
                }
                dbDaoHelper.insertOfflineWorkJob(workJobBean);
            }
        }
    }

    private void saveBuildJobManageInfo(RushRepairBean RushRepairBean, int state) {
        if (RushRepairBean != null) {
            RushRepairBean.setSubmit_state("" + state);
            dbDaoHelper.insertOrUpdateBuildJobManage(RushRepairBean);
        }
    }

    /**
     * 删除本地工单数据
     */
    public void deleteLocalBuildJobManage(RushRepairBean RushRepairBean, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> filesList) {
        dbDaoHelper.deleteRushRepair(RushRepairBean);

        if (pictures != null && pictures.size() > 0) {
            dbDaoHelper.deleteSavedTroublePictures(pictures);
            for (TroublePictureBean pictureBean : pictures) {
                String file = pictureBean.getFilepath();
                FileUtil.deleteFile(file);
            }
        }
        if (audios != null && audios.size() > 0) {
            dbDaoHelper.deleteSavedTroubleAudios(audios);
            for (TroubleAudioBean audioBean : audios) {
                String file = audioBean.getPath();
                FileUtil.deleteFile(file);
            }
        }
        if (filesList != null && filesList.size() > 0) {
            dbDaoHelper.deleteBuildFiles(filesList);
        }

        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(String.valueOf(RushRepairBean.getId()));
        if (workJobBean != null) {
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
        }
    }

    /**
     * 获取在线抢维修数据
     */

    public void getOnlineRepairList(Context context, final RushRepairCallback repairCallback) {
        getRushRepairList(context, true, repairCallback);
    }

    public void getLocalRepairList(Context context , final RushRepairCallback repairCallback) {
        getRushRepairList(context, false, repairCallback);
    }

    public void addRushProcessManage(Context context, RushRepairProcessBean data, List<TroublePictureBean> photos,
                                     List<Record> records, List<BuildFileBean> fileBeanList, RushRepairCallback repairCallback) {
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        if (fileBeanList != null && fileBeanList.size() > 0) {
            dbDaoHelper.saveBuildFiles(fileBeanList, "3", data.getId());
        }
        addRushManageProcess(context, data, photos, audioBeans, fileBeanList, true, repairCallback);
    }

    /**
     * 过程管理
     */
    public void addRushManageProcess(final Context context, final RushRepairProcessBean repairProcessBean, final List<TroublePictureBean> photos,
                                     final List<TroubleAudioBean> audios, final List<BuildFileBean> fileBeanList, final boolean saveOnFail, final RushRepairCallback repairCallback) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && repairProcessBean != null) {
//            saveRushProcessManageInfo(repairProcessBean);
            if (rushRepairController == null)
                rushRepairController = new RushRepairController(context);
            rushRepairController.addRushProcessManage(repairProcessBean, photos, audios, fileBeanList, new RushRepairCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    if (isSuccess) {
                        deleteLocalRushProcess(repairProcessBean, photos, audios, fileBeanList);
                    } else {
                        if (saveOnFail) {
                            repairProcessBean.setSubmit_state("" + BuildManageBean.BUILD_SUBMIT_ONE);
                            saveRushProcessInfo(repairProcessBean, photos, audios, fileBeanList);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getResources().getString(R.string.rush_repair_upload_info_err) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }
                    if (repairCallback != null)
                        repairCallback.onAddBuildManage(isSuccess, errorCode, errMsg);
                }
            });
        }
    }

    private void saveRushProcessManageInfo(RushRepairProcessBean repairProcessBean) {
        if (repairProcessBean != null) {
            repairProcessBean.setSubmit_state("" + BuildManageBean.BUILD_SUBMIT_ZERO);
            dbDaoHelper.insertOrUpdateRushRepairProcess(repairProcessBean);
        }
    }

    private void getRushRepairList(final Context context, boolean online, final RushRepairCallback repairCallback) {
        if (rushRepairController == null) {
            rushRepairController = new RushRepairController(context);
        }
        rushRepairController.getRushRepairList(online, 1, C.DEFAULT_MAX_LOAD_PAGESIZE, new RushRepairCallback() {

            @Override
            public void onRepairList(boolean isSuccess, int errorCode, String errMsg, List<RushRepairBean> buildManageList, int total) {
                super.onRepairList(isSuccess, errorCode, errMsg, buildManageList, total);
                if (isSuccess) {

                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    ToastUtil.showToast(context, errMsg);
                }
                if (repairCallback != null) {
                    repairCallback.onRepairList(isSuccess, errorCode, errMsg, buildManageList, total);
                }
            }
        });
    }

    public void updateRushProcessState(Context context, RushRepairBean rushRepairBean, RushRepairCallback repairCallback) {
        updateRushProcessState(context, rushRepairBean, true, repairCallback);
    }

    /**
     * 更新抢维修监护状态
     */
    private void updateRushProcessState(final Context context, final RushRepairBean rushRepairBean, final boolean saveOnFail, final RushRepairCallback repairCallback) {

        if (rushRepairController == null)
            rushRepairController = new RushRepairController(context);
        rushRepairController.updateRushProcessState(rushRepairBean, new RushRepairCallback() {
            @Override
            public void onRushBack(boolean isSuccess, int errorCode, String errMsg) {
                super.onRushBack(isSuccess, errorCode, errMsg);
                if (isSuccess) {

                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    ToastUtil.showToast(context, errMsg);
                }
                if (repairCallback != null)
                    repairCallback.onRushBack(isSuccess, errorCode, errMsg);
            }
        });
    }

    /**
     * 删除本地抢维修保存数据
     */
    public void deleteLocalRushProcess(RushRepairProcessBean buildManage, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> fileBeanList) {
        dbDaoHelper.deleteRushProcess(buildManage);

        if (pictures != null && pictures.size() > 0) {
            dbDaoHelper.deleteSavedTroublePictures(pictures);
            for (TroublePictureBean pictureBean : pictures) {
                String file = pictureBean.getFilepath();
                FileUtil.deleteFile(file);
            }
        }
        if (audios != null && audios.size() > 0) {
            dbDaoHelper.deleteSavedTroubleAudios(audios);
            for (TroubleAudioBean audioBean : audios) {
                String file = audioBean.getPath();
                FileUtil.deleteFile(file);
            }
        }
        if (fileBeanList != null && fileBeanList.size() > 0) {
            dbDaoHelper.deleteBuildFiles(fileBeanList);
        }

        OfflineWorkJobBean workJobBean = dbDaoHelper.getOfflineWorkJob(buildManage.getId());
        if (workJobBean != null) {
            dbDaoHelper.deleteOfflineWorkJob(workJobBean);
        }
    }

    /**
     * 保存过程管理
     */
    private void saveRushProcessInfo(RushRepairProcessBean buildManage, List<TroublePictureBean> pictures, List<TroubleAudioBean> audios, List<BuildFileBean> fileBeanList) {
        if (buildManage != null) {
            OfflineWorkJobBean workJobBean1 = dbDaoHelper.getOfflineWorkJob(buildManage.getId());
            if (workJobBean1 == null) {
                int save_state = BuildManageBean.BUILD_SUBMIT_ONE;
                OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
                String job_id = UUID.randomUUID().toString();
                workJobBean.setId(job_id);
                workJobBean.setJob_type(OfflineWorkJobBean.OfflineWorkJobType.JOB_RUSH_REPAIR_PROCESS);
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                workJobBean.setUser_id(userBean.getUserid());

                /*保存隐患的数据信息*/
                buildManage.setSubmit_state("" + save_state);
                dbDaoHelper.insertOrUpdateRushRepairProcess(buildManage);

                workJobBean.setRef_id(buildManage.getId());

                /*保存隐患的图片*/
                if (pictures != null && pictures.size() > 0) {
                    List<String> pic_ids = new ArrayList<>();
                    for (TroublePictureBean pictureBean : pictures) {
                        if (pictureBean != null && FileUtil.fileExists(pictureBean.getFilepath())) {
                            String id = UUID.randomUUID().toString();
                            pictureBean.setId(id);
                            pictureBean.setTroubleid(buildManage.getWorkOrderId());
                            pictureBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateTroublePicture(pictureBean);

                            pic_ids.add(id);
                        }
                    }
                    workJobBean.setRef_photo_ids(pic_ids);
                }

                /*保存隐患的音频*/
                String filetype = "amr";
                if (audios != null && audios.size() > 0) {
                    List<String> audio_ids = new ArrayList<>();
                    for (TroubleAudioBean audioBean : audios) {
                        if (audioBean != null && FileUtil.fileExists(audioBean.getPath())) {
                            String audioId = UUID.randomUUID().toString();
                            audioBean.setId(audioId);
                            audioBean.setTroubleid(buildManage.getWorkOrderId());
                            audioBean.setFiletype(filetype);
                            audioBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateTroubleAudio(audioBean);

                            audio_ids.add(audioId);
                        }
                    }
                    workJobBean.setRef_audio_ids(audio_ids);
                }

                /*保存抢维修附件*/
                if (fileBeanList != null && fileBeanList.size() > 0) {
                    List<String> file_id = new ArrayList<>();
                    for (BuildFileBean fileBean : fileBeanList) {
                        if (fileBean != null && FileUtil.fileExists(fileBean.getFilePath())) {
                            fileBean.setRepairProcessId(buildManage.getWorkOrderId());
                            fileBean.setStatus(save_state);
                            dbDaoHelper.insertOrUpdateBuildFiles(fileBean);
                            file_id.add(fileBean.getId());
                        }
                    }
                    workJobBean.setRef_data_ids(file_id);
                }
                dbDaoHelper.insertOfflineWorkJob(workJobBean);
            }
        }
    }

}
