package com.tofly.ghrq_route.module.uploadPhoto;

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.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.systemConfig.SystemConfigTool;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigCallBack;
import com.tofly.ghrq_route.module.systemConfig.domain.ServerSysConfigBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.uploadPhoto.controller.UploadPhotoCallBack;
import com.tofly.ghrq_route.module.uploadPhoto.controller.UploadPhotoController;
import com.tofly.ghrq_route.module.uploadPhoto.domain.ReportedPhotoBean;
import com.tofly.ghrq_route.module.uploadPhoto.domain.UploadPhotoBean;
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.FileUtil;

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

/**
 * Created by Amu on 2017/4/26.
 */

public class UploadPhotoTool {

    private static final String TAG = UploadPhotoTool.class.getName();

    private static UploadPhotoTool uploadPhotoTool = null;

    private SystemConfigTool systemConfigTool;

    private DBDaoHelper dbDaoHelper;

    private UploadPhotoController uploadPhotoController;

    private UploadPhotoTool(){
        dbDaoHelper = DBDaoHelper.getInstance();
        systemConfigTool = SystemConfigTool.getInstance();
    }

    public static synchronized UploadPhotoTool getInstance(){
        if (uploadPhotoTool == null){
            uploadPhotoTool = new UploadPhotoTool();
        }
        return uploadPhotoTool;
    }

    public void getPhotoTypeConfigList(final Context context, final ServerSysConfigCallBack serverSysConfigCallBack){
        systemConfigTool.getPhotoTypeConfigList(context, new ServerSysConfigCallBack(){
            @Override
            public void onGetSysConfigList(boolean isSuccess, int errorCode, String errMsg, List<ServerSysConfigBean> configList, int total) {
                super.onGetSysConfigList(isSuccess, errorCode, errMsg, configList, total);

                if (serverSysConfigCallBack != null)
                    serverSysConfigCallBack.onGetSysConfigList(isSuccess, errorCode, errMsg, configList, total);
            }
        });
    }

    /*保存隐患数据*/
    public void saveUploadPhoto(UploadPhotoBean photoBean, List<TroublePictureBean> pictureBeans, List<TroubleAudioBean> audioBeans) {
        if (photoBean != null) {
            /*保存隐患的数据信息*/
            String troubleId = UUID.randomUUID().toString();
            photoBean.setId(troubleId);
            photoBean.setFindTime(DateUtils.getCurrentDate());
            photoBean.setState(TroubleBean.SAVED_STATE);
            if (photoBean.getUserid() == null || photoBean.getUserid().isEmpty()) {
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                if (userBean != null)
                    photoBean.setUserid(userBean.getUserid());
            }
            dbDaoHelper.insertOrUpdateUploadPhoto(photoBean);

            OfflineWorkJobBean workJobBean = new OfflineWorkJobBean();
            String job_id = UUID.randomUUID().toString();
            workJobBean.setId(job_id);
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            workJobBean.setUser_id(userBean.getUserid());
            workJobBean.setJob_type(OfflineWorkJobBean.OfflineWorkJobType.JOB_UPLOAD_PHOTO_ADD);
            workJobBean.setRef_id(troubleId);

            /*保存隐患的图片*/
            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(troubleId);
                        pictureBean.setStatus(TroubleBean.SAVED_STATE);
                        dbDaoHelper.insertOrUpdateTroublePicture(pictureBean);

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

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

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

            dbDaoHelper.insertOfflineWorkJob(workJobBean);
        }
    }

    public void saveUploadPhotoWithRecords(UploadPhotoBean photoBean, List<TroublePictureBean> pictureBeans, List<Record> records) {
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        saveUploadPhoto(photoBean, pictureBeans, audioBeans);
    }

    private void removeLocalTroublePhotoAudio(UploadPhotoBean photoBean, List<TroublePictureBean> pictureBeans, List<TroubleAudioBean> audioBeans){
        if (photoBean != null)
            dbDaoHelper.deleteSavedUploadPhoto(photoBean);

        /*删除本地隐患的图片*/
        for (TroublePictureBean pictureBean : pictureBeans) {
            if (pictureBean != null) {
                dbDaoHelper.deleteSavedTroublePicture(pictureBean);
                FileUtil.deleteFile(pictureBean.getFilepath());
            }
        }

        /*删除本地隐患的音频*/
        for (TroubleAudioBean audioBean : audioBeans){
            if (audioBean != null) {
                dbDaoHelper.deleteSavedTroubleAudio(audioBean);
                FileUtil.deleteFile(audioBean.getPath());
            }
        }

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

    private void saveTroubleBean(UploadPhotoBean photoBean, int state){
        if (photoBean != null) {
            photoBean.setState(state);
            dbDaoHelper.insertOrUpdateUploadPhoto(photoBean);
        }
    }

    public void uploadPhotoNew(final Context context, final UploadPhotoBean photoBean, final List<TroublePictureBean> photos,
                               final List<TroubleAudioBean> audios, final boolean saveOnFail, final UploadPhotoCallBack uploadPhotoCallBack) {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null && photoBean != null) {
            saveTroubleBean(photoBean, TroubleBean.SAVE_UPLOADING_STATE);
            if (uploadPhotoController == null)
                uploadPhotoController = new UploadPhotoController(context);
            photoBean.setFindTime(DateUtils.getCurrentDate());
            uploadPhotoController.addUploadPhotoNew(userBean.getToken(), photoBean, photos, audios,  new UploadPhotoCallBack() {
                @Override
                public void onAddUploadPhotoInfo(boolean isSuccess, int errorCode, String errMsg, String troubleId) {
                    super.onAddUploadPhotoInfo(isSuccess, errorCode, errMsg, troubleId);
                    if (isSuccess) {
                        removeLocalTroublePhotoAudio(photoBean, photos, audios);
                    } else {
                        if (saveOnFail)
                            saveUploadPhoto(photoBean, photos, audios);
                        else {
                            saveTroubleBean(photoBean, TroubleBean.SAVED_STATE);
                        }
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        String strWarn = context.getString(R.string.dangerreport_next_upload_error) + errMsg;
                        ToastUtil.showToast(context, strWarn);
                    }

                    if (uploadPhotoCallBack != null){
                        uploadPhotoCallBack.onAddUploadPhotoInfo(isSuccess, errorCode, errMsg, troubleId);
                    }
                }
            });
        }
    }

    public void uploadPhotoNew(final Context context, final UploadPhotoBean photoBean, final List<TroublePictureBean> photos,
                               final List<Record> records, final UploadPhotoCallBack uploadPhotoCallBack){
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(records);
        uploadPhotoNew(context, photoBean, photos, audioBeans, true, uploadPhotoCallBack);
    }

    public void uploadNewPhotoNoSave(final Context context, final UploadPhotoBean photoBean, final List<TroublePictureBean> photos,
                                     final List<TroubleAudioBean> audios, final UploadPhotoCallBack uploadPhotoCallBack){
        uploadPhotoNew(context, photoBean, photos, audios, false, uploadPhotoCallBack);
    }

    public List<UploadPhotoBean> getSavedUploadPhotos(){
        List<UploadPhotoBean> savedUploadPhotos = null;
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            savedUploadPhotos = dbDaoHelper.getUploadPhotoList(userBean.getUserid(), TroubleBean.SAVED_STATE);
        }
        return savedUploadPhotos;
    }

    public List<TroublePictureBean> getSavedTroublePictures(String troubleId){
        return dbDaoHelper.queryTroublePictures(troubleId);
    }

    public List<TroubleAudioBean> getSavedTroubleAudios(String troubleId){
        return dbDaoHelper.queryTroubleAudios(troubleId);
    }

    public TroubleAudioBean getTroubleAudio(String url){
        return dbDaoHelper.queryTroubleAudio(url);
    }

    /*从服务器获取隐患列表*/
    public void getReportedPhotoListOnline(Context context, String picTypeId, String departId, String userId, int pageindex, UploadPhotoCallBack uploadPhotoCallBack){
        getReportedPhotoList(context, picTypeId, departId, userId, pageindex, uploadPhotoCallBack);
    }

    public void getReportedPhotoList(final Context context, String picTypeId, String departId, String userId, int pageindex, final UploadPhotoCallBack uploadPhotoCallBack){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        final int pagesize = C.DEFAULT_LOAD_PAGESIZE;
        if (userBean != null){
            if (uploadPhotoController == null)
                uploadPhotoController = new UploadPhotoController(context);
            uploadPhotoController.getReportedPhoto(context, picTypeId, departId, userId, pageindex, pagesize, new UploadPhotoCallBack(){
                @Override
                public void onGetReportedPhoto(boolean isSuccess, int errorCode, String errMsg, List<ReportedPhotoBean> photoList, int total) {
                    super.onGetReportedPhoto(isSuccess, errorCode, errMsg, photoList, total);
                    if (isSuccess){
                    }else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        ToastUtil.showToast(context, errMsg);
                    }

                    if (uploadPhotoCallBack != null)
                        uploadPhotoCallBack.onGetReportedPhoto(isSuccess, errorCode, errMsg, photoList, total);
                }
            });
        }
    }
}
