package kz.arta.synergy.workflow.mobile.android.works.activities;

import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.devspark.appmsg.AppMsg;
import com.google.gson.JsonSyntaxException;
import com.pnikosis.materialishprogress.ProgressWheel;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.attachments.activities.AttachmentList;
import kz.arta.synergy.workflow.mobile.android.comments.CommentConst;
import kz.arta.synergy.workflow.mobile.android.comments.activities.AddCommentActivity;
import kz.arta.synergy.workflow.mobile.android.comments.activities.CommentsList;
import kz.arta.synergy.workflow.mobile.android.common.ActivityConst;
import kz.arta.synergy.workflow.mobile.android.common.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.components.AButton;
import kz.arta.synergy.workflow.mobile.android.common.components.CustomImageView;
import kz.arta.synergy.workflow.mobile.android.common.components.OpenFileDialog;
import kz.arta.synergy.workflow.mobile.android.common.models.ErrorCode;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.offline.add.AddAttachment;
import kz.arta.synergy.workflow.mobile.android.common.offline.add.AddChangeProgress;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.FormCompletionTable;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorkActionsTable;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorkCommentsTable;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorksTable;
import kz.arta.synergy.workflow.mobile.android.common.requests.RestClient;
import kz.arta.synergy.workflow.mobile.android.common.requests.SendGetRequest;
import kz.arta.synergy.workflow.mobile.android.common.utils.ActionUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Const;
import kz.arta.synergy.workflow.mobile.android.common.utils.DateUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.ImageLoader;
import kz.arta.synergy.workflow.mobile.android.common.utils.MyApplication;
import kz.arta.synergy.workflow.mobile.android.common.utils.StatusWork;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Wrapper;
import kz.arta.synergy.workflow.mobile.android.documents.common.models.DocumentItem;
import kz.arta.synergy.workflow.mobile.android.documents.resolution.activities.ActionResolutionActivity;
import kz.arta.synergy.workflow.mobile.android.files.FilesConst;
import kz.arta.synergy.workflow.mobile.android.files.activities.FilesTreeActivity;
import kz.arta.synergy.workflow.mobile.android.files.manager.DownloadFile;
import kz.arta.synergy.workflow.mobile.android.files.manager.FilesManager;
import kz.arta.synergy.workflow.mobile.android.files.manager.UploadFile;
import kz.arta.synergy.workflow.mobile.android.files.models.Node;
import kz.arta.synergy.workflow.mobile.android.forms.general.activities.FormPlayer;
import kz.arta.synergy.workflow.mobile.android.works.activities.completion.CompletionWorkCommentActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.completion.CompletionWorkFileActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.completion.CompletionWorkFormActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.completion.ResultWorkActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.completion.process.FinishProcessActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.send.SendWorkActivity;
import kz.arta.synergy.workflow.mobile.android.works.activities.send.TransmitWorkActivity;
import kz.arta.synergy.workflow.mobile.android.works.manager.completion.CompletionWorkForm;
import kz.arta.synergy.workflow.mobile.android.works.models.CompletionFormItem;
import kz.arta.synergy.workflow.mobile.android.works.models.CompletionResultItem;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkActionsItem;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkItem;

/**
 * Created by neox on 07.04.14.
 * Информация о работе.
 */
public class WorkInfoActivity extends Activity {

    /**
     * Данные для авторизированного пользователя
     */
    private Person person;

    /**
     * Активити
     */
    private Activity activity;

    /**
     * Настройки
     */
    private SharedPreferences settings;

    /**
     * Главный контейнер (ScrollView with PullToRefresh)
     */
    private SwipeRefreshLayout mainContent;

    /**
     * Прогрессбар
     */
    private ProgressWheel progressBar;

    /**
     * Текущая работа
     */
    private WorkItem work;

    /**
     * Идентификатор работы
     */
    private String workID;

    /**
     * Имя файла для изображения сделанного с помощью камеры (в миллисекундах)
     */
    private long photoFileName;

    /**
     * Здесь хранится начальное значение прогресса (в случае если пользователь в диалоге нажал "Нет" - нужно вернуть старое значение прогресса)
     */
    private int workPercent;

    /**
     * Действия, которые пользователь может делать с работой (Отправить на согласование, ознакомление и т.д)
     */
    private WorkActionsItem[] workActions;

    /**
     * Форма завершения текущей работы (FORM, COMMENT, FILE)
     */
    private String formCompletion;

    /**
     * uuid формы завершения текущей работы
     */
    private String formID;

    /**
     * Статус работы (На согласовании, На рассмотрении)
     */
    private TextView statusWorkLabel;

    /**
     * Прогресс работы
     */
    private SeekBar progressWork;

    /**
     * Прогресс работы (лейбл)
     */
    private TextView progressWorkLabel;

    /**
     * Диалог с прогрессом (используется при открытии файла либо при добавлении)
     */
    private ProgressDialog addFileProgress;

    /**
     * Кнопка для загрузки комментариев для работы
     */
    private Button workButton;

    /**
     * Кнопка для загрузки комментариев для документа
     */
    private Button documentButton;

    /**
     * Кнопка для загрузки личных комментариев
     */
    private Button personalButton;

    /**
     * Документ (заполняется в том случае, если работа завершена)
     */
    private DocumentItem document;

    /**
     * Данные о форме завершения работы
     */
    private CompletionFormItem formCompletionDesc;

    /**
     * Контейнер для кнопок
     */
    private LinearLayout actions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.work_info_activity);

        activity = this;

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        workID = (String) intent.getSerializableExtra(ActivityConst.WORK_ID);

        settings = getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);

        progressBar = (ProgressWheel) findViewById(R.id.info_work_progress_bar);

        // основной контейнер для всех компонентов
        mainContent = (SwipeRefreshLayout) findViewById(R.id.work_info_refresh_layout);
        mainContent.setColorSchemeResources(R.color.color1_update_list, R.color.color2_update_list,
                R.color.color3_update_list, R.color.color4_update_list);
        mainContent.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mainContent.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Utils.isOnline(activity, person.getHost())) {
                            // при обновлении экрана - заного грузим все данные
                            getFullData();
                        } else {
                            mainContent.setRefreshing(false);
                        }
                    }
                }, 0);
            }
        });

        CustomImageView addButton = (CustomImageView) findViewById(R.id.work_info_add_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showActionsDialog();
            }
        });

        // для информации о работе по умолчанию идет загрузка комментариев для работы
        CommentsList.commentType = CommentConst.WORK;

        // верхние кнопки для работы с комментариями
        initCommentsButton();

        // загружаем полную информацию о работе (комменты, вложения, кнопки)
        getFullData();

    }

    /**
     * Метод отображает диалог с пунктами добавления чего-либо к работе
     */
    private void showActionsDialog() {
        // fucking hardcode .............
        if (Utils.isOnline(getBaseContext(), person.getHost())) {
            String[] items = {
                    getString(R.string.file_from_storage),
                    getString(R.string.file_from_camera),
                    getString(R.string.photo),
                    getString(R.string.comment)
            };
            AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
            dialog.setTitle(R.string.add);
            dialog.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, final int pos) {
                    switch (pos) {
                        case 0: {
                            addFileFromStorage();
                            break;
                        }
                        case 1: {
                            addFileFromDevice();
                            break;
                        }
                        case 2: {
                            addFileFromCamera();
                            break;
                        }
                        case 3: {
                            addComment();
                            break;
                        }
                    }
                }
            });
            dialog.setCancelable(true);
            dialog.show();
        } else {
            String[] items = {
                    getString(R.string.file_from_camera),
                    getString(R.string.photo),
                    getString(R.string.comment)
            };
            AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
            dialog.setTitle(R.string.add);
            dialog.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, final int pos) {
                    switch (pos) {
                        case 0: {
                            addFileFromDevice();
                            break;
                        }
                        case 1: {
                            addFileFromCamera();
                            break;
                        }
                        case 2: {
                            addComment();
                            break;
                        }
                    }
                }
            });
            dialog.setCancelable(true);
            dialog.show();
        }
    }

    /**
     * Метод используется для добавления нового комментария к работе
     */
    private void addComment() {
        Intent intent = new Intent(activity, AddCommentActivity.class);
        intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
        intent.putExtra(ActivityConst.PERSON, person);
        intent.putExtra(ActivityConst.WORK_NAME, work.getName());
        intent.putExtra(ActivityConst.EDIT, false);
        intent.putExtra(ActivityConst.COMMENT_TYPE, CommentsList.commentType);
        startActivityForResult(intent, ActionUtils.COMMENT);
    }

    /**
     * Метод используется для проверки разрешений к Камере
     */
    public boolean isCameraPermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 101);
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * Метод используется для добавления нового файла к работе с камеры
     */
    private void addFileFromCamera() {
        File folder = new File(Environment.getExternalStorageDirectory() +
                File.separator + Const.DIRECTORY_PHOTOS_NAME + File.separator);
        boolean createdDir = true;
        if (!folder.exists()) {
            createdDir = folder.mkdir();
        }
        if (createdDir) {
            photoFileName = System.currentTimeMillis();
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uriSavedImage = Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
                    File.separator + Const.DIRECTORY_PHOTOS_NAME + File.separator + photoFileName + Const.DEFAULT_FILE_FORMAT));
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);

            //UPD: 2023-11-11 - добавил проверку разрешений, иначе приложение крашится
            if (isCameraPermissionGranted()) {
                startActivityForResult(cameraIntent, ActionUtils.PHOTO);
            }
        }
    }

    /**
     * Метод используется для добавления нового файла к работе с устройства
     */
    private void addFileFromDevice() {
        final OpenFileDialog fileDialog = new OpenFileDialog(activity);
        fileDialog.setOpenDialogListener(new OpenFileDialog.OpenDialogListener() {
            @Override
            public void OnSelectedFile(String fileName) {
                if (Utils.isOnline(activity, person.getHost())) {
                    AddFile add = new AddFile();
                    add.setFileName(new File(fileName).getName());
                    add.setFilePath(fileName);
                    add.setWorkID(work.getActionID());
                    add.execute();
                } else if (Utils.checkSyncEnables(settings)) {
                    AddAttachment add = new AddAttachment(activity);
                    add.add(work.getActionID(), fileName,
                            String.valueOf(System.currentTimeMillis()), work.getName(), new File(fileName).getName());
                    getAttachments();
                    getActions();
                }
            }
        });
        fileDialog.show();
    }

    /**
     * Метод используется для открытия экрана добавления нового файла к работе из хранилища
     */
    private void addFileFromStorage() {
        Intent intent = new Intent(activity, FilesTreeActivity.class);
        intent.putExtra(FilesConst.SHOW_FILES, true);
        intent.putExtra(ActivityConst.PERSON, person);
        startActivityForResult(intent, ActionUtils.UPLOAD_FILE_FROM_STORAGE);
    }

    /**
     * Метод принимает на вход объект "работа", и выставляет соответствующий текст в информацию о работе (автор, дата и т.д)
     *
     * @param work - работа
     */
    private void setData(final WorkItem work) {

        if (work == null) {
            return;
        }

        workPercent = Integer.parseInt(work.getPercent());

        TextView workText = (TextView) findViewById(R.id.work_info_work_name);
        workText.setText(work.getName());
        workText.setTypeface(Fonts.getRoman(activity));

        if (work.getIs_expired().equals("true")) {
            workText.setTextColor(activity.getResources().getColor(R.color.expired_color_work));
        } else if (work.getIs_soon_expired().equals("true")) {
            workText.setTextColor(activity.getResources().getColor(R.color.soon_expired_color_work));
        } else {
            workText.setTextColor(activity.getResources().getColor(R.color.default_color_work));
        }

        TextView authorLabel = (TextView) findViewById(R.id.work_info_author_label);
        authorLabel.setTypeface(Fonts.getRoman(activity));
        authorLabel.setVisibility(View.VISIBLE);

        TextView author = (TextView) findViewById(R.id.work_info_author);
        author.setText(work.getAuthor().getName());
        author.setTypeface(Fonts.getMedium(activity));

        if (work.getAuthor().getName() == null || work.getAuthor().getName().isEmpty()) {
            authorLabel.setVisibility(View.GONE);
            author.setVisibility(View.GONE);
        }

        TextView responsibleLabel = (TextView) findViewById(R.id.work_info_responsible_label);
        responsibleLabel.setTypeface(Fonts.getRoman(activity));
        responsibleLabel.setVisibility(View.VISIBLE);

        TextView responsible = (TextView) findViewById(R.id.work_info_responsible);
        responsible.setText(work.getUser().getName());
        responsible.setTypeface(Fonts.getMedium(activity));

        if (work.getUser().getName() == null || work.getUser().getName().isEmpty()) {
            responsibleLabel.setVisibility(View.GONE);
            responsible.setVisibility(View.GONE);
        }

        TextView startDate = (TextView) findViewById(R.id.work_info_start_date);
        startDate.setText(DateUtils.parseDateWorkInfo(work.getStart_date(), activity));
        startDate.setTypeface(Fonts.getRoman(activity));

        TextView finishDate = (TextView) findViewById(R.id.work_info_finish_date);
        finishDate.setText(" - " + DateUtils.parseDateWorkInfo(work.getFinish_date(), activity));
        finishDate.setTypeface(Fonts.getRoman(activity));

        progressWorkLabel = (TextView) findViewById(R.id.work_info_seek_bar_label);
        progressWorkLabel.setText(work.getPercent() + "%");
        progressWorkLabel.setTypeface(Fonts.getMedium(activity));
        progressWorkLabel.setVisibility(View.VISIBLE);

        progressWork = (SeekBar) findViewById(R.id.work_info_seek_bar);
        progressWork.setProgress(Integer.parseInt(work.getPercent()));
        progressWork.setVisibility(View.VISIBLE);
        progressWork.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                progressWorkLabel.setText(seekBar.getProgress() + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                workPercent = seekBar.getProgress();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // если прогресс меньше 100 - изменяем прогресс
                if (seekBar.getProgress() < 100) {
                    changeProgressDialog();
                } else if (formCompletion != null && !formCompletion.equals("NOTHING")) {
                    switch (formCompletion) {
                        case ActivityConst.FILE: {
                            ActionUtils.openActivityCompletionWorkFile(activity, person, work);
                            break;
                        }
                        case ActivityConst.COMMENT: {
                            ActionUtils.openActivityCompletionWorkComment(activity, person, work);
                            break;
                        }
                        case ActivityConst.FORM: {
                            if (Utils.isOnline(activity, person.getHost())) {
                                ActionUtils.openActivityCompletionWorkForm(activity, person, work, formID, progressBar);
                            }
                            break;
                        }
                    }
                } else {
                    finishWorkDialog();
                }
            }
        });

        // если нет прав изменять прогресс - отключаем его
        if (!work.getCan_change_progress().equals("true")) {
            progressWork.setEnabled(false);
        }

        statusWorkLabel = (TextView) findViewById(R.id.work_info_status);
        statusWorkLabel.setTypeface(Fonts.getMedium(activity));

        // проверяем статус работы
        StatusWork statusWork = new StatusWork();
        statusWork.setActivity(activity);
        statusWork.setSeekBar(progressWork);
        statusWork.setProgressText(progressWorkLabel);
        statusWork.setStatusWork(statusWorkLabel);
        statusWork.checkStatus(work);
    }

    /**
     * Инициализация кнопок для работы с комментариями
     */
    private void initCommentsButton() {

        workButton = (Button) findViewById(R.id.comments_work);
        documentButton = (Button) findViewById(R.id.comments_document);
        personalButton = (Button) findViewById(R.id.comments_personal);

        workButton.setTypeface(Fonts.getRoman(activity));
        workButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButton.setBackgroundResource(R.drawable.comments_button_left_selected);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                CommentsList.commentType = CommentConst.WORK;
                getComments();
            }
        });

        documentButton.setTypeface(Fonts.getRoman(activity));
        documentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center_selected);
                personalButton.setBackgroundResource(R.drawable.comments_button_right);
                CommentsList.commentType = CommentConst.DOCUMENT;
                getComments();
            }
        });

        personalButton.setTypeface(Fonts.getRoman(activity));
        personalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButton.setBackgroundResource(R.drawable.comments_button_left);
                documentButton.setBackgroundResource(R.drawable.comments_button_center);
                personalButton.setBackgroundResource(R.drawable.comments_button_right_selected);
                CommentsList.commentType = CommentConst.PERSONAL;
                getComments();
            }
        });
    }

    /**
     * Метод загружает все данные для работы (комментарии, вложения, формы заврешения, действия)
     */
    public void getFullData() {
        new SendGetRequest("rest/api/workflow/works_by_id?workID=" + workID, person) {
            @Override
            protected void onPostExecute(String result) {
                try {
                    WorkItem[] works = RestClient.getGson().fromJson(result, WorkItem[].class);
                    work = works[0];
                    setData(work);
                    getDocumentID();
                    getWorkFormCompletionResult();
                    getComments();
                    getAttachments();
                } catch (Exception exc) {
                    if (Utils.checkSyncEnables(settings)) {
                        try {
                            WorksTable worksTable = new WorksTable(activity);
                            work = worksTable.getWorkInfo(workID);
                            setData(work);
                            getWorkFormCompletionResult();
                            getComments();
                            getAttachments();
                            getActions();
                        } catch (Exception e) {
                            progressBar.setVisibility(View.GONE);
                            mainContent.setRefreshing(false);
                            AppMsg.makeText(activity, getString(R.string.error_to_get_work), AppMsg.STYLE_ALERT).show();
                        }
                    } else {
                        progressBar.setVisibility(View.GONE);
                        mainContent.setRefreshing(false);
                        AppMsg.makeText(activity, getString(R.string.error_to_get_work), AppMsg.STYLE_ALERT).show();
                    }
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод получает для текущей работы documentID
     */
    private void getDocumentID() {
        new SendGetRequest("rest/api/workflow/work/" + work.getActionID() + "/document", person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    return;
                }
                try {
                    String documentID = RestClient.getGson().fromJson(result, DocumentID.class).documentID;
                    document = new DocumentItem();
                    document.setDocumentID(documentID);
                    getActions();
                } catch (Exception exc) {
                    AppMsg.makeText(activity, getString(R.string.error_download_actions), AppMsg.STYLE_ALERT).show();
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод получает список подписей для документа
     *
     * @param documentID идентификатор документа
     */
    private void getSignList(String documentID) {
        new SendGetRequest("rest/api/docflow/doc/sign_list?documentID=" + documentID, person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    return;
                }
                try {
                    JSONArray jsonArray = new JSONArray(result);
                    boolean addSignButton = true;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        String userID = object.getString("userID");
                        if (userID.equals(person.getUuid())) {
                            addSignButton = false;
                            break;
                        }
                    }
                    if (addSignButton) {
                        if (!work.getParent_process().equals("agreement-single") &&
                                !work.getParent_process().equals("approval-single") &&
                                    !work.getParent_process().equals("acquaintance-single")) {
                            AButton sign = new AButton(activity);
                            sign.setText("Подписать");
                            sign.setBackground(AButton.GRAY);
                            sign.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (person.getSettings().isNeedCert() && !person.getSettings().isEnableEDS()) {
                                        AppMsg.makeText(activity, getString(R.string.eds_not_installed), AppMsg.STYLE_ALERT).show();
                                        return;
                                    }
                                    Intent intent = new Intent(activity, FinishProcessActivity.class);
                                    intent.putExtra(ActivityConst.PERSON, person);
                                    intent.putExtra(ActivityConst.DOCUMENT_ID, document.getDocumentID());
                                    startActivityForResult(intent, ActionUtils.PROCESS_FINISH_INFO);
                                }
                            });
                            actions.addView(sign);
                        }
                    }
                } catch (Exception exc) {
                    // handling error ...
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Получение действий
     */
    public void getActions() {
        // для завершенной работы получаем действия по отношению к документу
        if (work.getStateID().equals(ActionUtils.STATE_COMPLETION)) {
            if (document != null && document.getDocumentID() != null) {
                getActions("rest/api/docflow/document_actions?documentID=" +
                        document.getDocumentID() + "&locale=" + MyApplication.getLang());
            }
        } else {
            if (work != null && work.getActionID() != null) {
                getActions("rest/api/workflow/work_actions?workID=" +
                        work.getActionID() + "&locale=" + MyApplication.getLang());
            }
        }
    }

    /**
     * Метод отвечает за загрузку и отображение блока "Результат завершения работы"
     */
    private void getWorkFormCompletionResult() {
        new SendGetRequest("rest/api/workflow/work/completion_result?workID=" + work.getActionID() +
                "&locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPreExecute() {
                findViewById(R.id.work_info_completion_result_comment).setVisibility(View.GONE);
                findViewById(R.id.work_info_completion_result_file).setVisibility(View.GONE);
                findViewById(R.id.form_completion_panel).setVisibility(View.GONE);
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    try {
                        CompletionResultItem completionResultItem = RestClient.getGson().fromJson(result, CompletionResultItem.class);
                        if (completionResultItem.getType().equals(ActivityConst.FORM) || completionResultItem.getType().equals(ActivityConst.FILE)) {
                            showCompletionFileBlock(completionResultItem);
                        } else {
                            showCompletionCommentBlock(completionResultItem, false);
                        }
                    } catch (Exception exc) {
                        // если работа не завершенная проверяем какая у нее форма завершения
                        getFormCompletion();
                    }
                } else if (Utils.checkSyncEnables(settings)) {
                    CompletionResultItem form = new FormCompletionTable(activity.getBaseContext()).getByWorkId(workID);
                    if (form.getTypeWork().equals("NO_COMPLETION")) {
                        formCompletion = form.getType();
                        showPanelFormType(Utils.getFormCompletion(work.getCompletionFormID(), person, activity, false));
                    } else if (form.getTypeWork().equals("COMPLETION")) {
                        if (form.getType().equals(ActivityConst.FORM) || form.getType().equals(ActivityConst.FILE)) {
                            showCompletionFileBlock(form);
                        } else {
                            showCompletionCommentBlock(form, true);
                        }
                    }
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод отображает панель с формой завершения у работы
     */
    private void showPanelFormType(String text) {

        Spannable ss = new SpannableString(activity.getString(R.string.form_completion) + ": " + text);
        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.default_darken_gray)), 0,
                getResources().getString(R.string.form_completion).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        RelativeLayout formCompletionBlock = (RelativeLayout) findViewById(R.id.form_completion_panel);

        TextView formCompletionName = (TextView) formCompletionBlock.findViewById(R.id.form_completion_name);
        formCompletionName.setTypeface(Fonts.getMedium(activity));
        formCompletionName.setText(ss);

        formCompletionBlock.setVisibility(View.VISIBLE);
    }

    /**
     * Отображает блок формы завершения файл
     *
     * @param result - форма завершения
     */
    private void showCompletionFileBlock(CompletionResultItem result) {

        RelativeLayout resultBlock = (RelativeLayout) findViewById(R.id.work_info_completion_result_file);

        ((TextView) resultBlock.findViewById(R.id.work_info_completion_result_file_title)).setTypeface(Fonts.getMedium(activity));

        ImageView icon = (ImageView) resultBlock.findViewById(R.id.work_info_completion_result_file_attach_icon);
        ImageLoader imageLoader = new ImageLoader(activity, person);

        TextView attachName = (TextView) resultBlock.findViewById(R.id.work_info_completion_result_file_attach_title);
        attachName.setTypeface(Fonts.getMedium(activity));

        final String fileName;
        final String fileUUID = result.getFileUUID();
        final String dataUUID = result.getDataUUID();

        attachName.setText(result.getFile_name());
        fileName = result.getFile_name();
        imageLoader.displayImage(person.getHost() + result.getFile_icon(), icon);

        resultBlock.setVisibility(View.VISIBLE);
        resultBlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dataUUID != null) {
                    // todo здесь по идее надо проверять есть ли у формы мобильное представление..
                    Intent intent = new Intent(activity, FormPlayer.class);
                    intent.putExtra(ActivityConst.DATA_UUID, dataUUID);
                    intent.putExtra(ActivityConst.PERSON, person);
                    intent.putExtra(ActivityConst.CAN_EDIT, "true");
                    startActivityForResult(intent, ActionUtils.SAVE_FORM);
                } else {
                    DownloadFile downloadFile = new DownloadFile(activity, person);
                    downloadFile.setFileName(fileName);
                    downloadFile.setUrl(person.getHost() + "rest/api/storage/pdf/get?identifier=" + fileUUID);
                    downloadFile.execute();
                }
            }
        });
    }

    /**
     * Отображает блок формы завершения комментарий
     *
     * @param result - форма завершения
     */
    private void showCompletionCommentBlock(CompletionResultItem result, boolean offline) {

        RelativeLayout completionWorkCommentBlock = (RelativeLayout) findViewById(R.id.work_info_completion_result_comment);

        ((TextView) completionWorkCommentBlock.findViewById(R.id.work_info_completion_result_comment_title)).setTypeface(Fonts.getMedium(activity));

        TextView author = (TextView) completionWorkCommentBlock.findViewById(R.id.work_info_completion_result_comment_user);
        author.setTypeface(Fonts.getMedium(activity));
        author.setText(result.getUser_name());

        TextView comment = (TextView) completionWorkCommentBlock.findViewById(R.id.work_info_completion_result_comment_text);
        comment.setTypeface(Fonts.getRoman(activity));
        comment.setText(result.getComment());

        TextView time = (TextView) completionWorkCommentBlock.findViewById(R.id.work_info_completion_result_comment_time);
        time.setTypeface(Fonts.getMedium(activity));

        if (offline) {
            try {
                time.setText(DateUtils.parseDateOfflineComment(Long.parseLong(result.getCreated()), activity));
            } catch (Exception exc) {
                time.setText(result.getCreated());
            }
        } else {
            time.setText(result.getCreated());
        }

        completionWorkCommentBlock.setVisibility(View.VISIBLE);
    }

    /**
     * Метод отвечает за загрузку и отображение блока "Форма завершения работы"
     */
    private void getFormCompletion() {
        new SendGetRequest("rest/api/workflow/work/get_completion_data?workID=" + work.getActionID() + "&locale=" +
                MyApplication.getLang(), person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    return;
                }
                try {
                    formCompletionDesc = RestClient.getGson().fromJson(result, CompletionFormItem.class);
                    formCompletion = formCompletionDesc.getResult().getType();
                    if (formCompletion.equals(ActivityConst.FORM) && formCompletionDesc.getForm_params().length != 0) {
                        formID = formCompletionDesc.getForm_params()[0].getFormID();
                        if (formID == null || formID == "") {
                            formID = formCompletionDesc.getForm_params()[1].getFormID();
                            if (formID == null || formID == "") {
                                formID = formCompletionDesc.getForm_params()[2].getFormID();
                            }
                        }
                    }
                    showPanelFormType(Utils.getFormCompletion(work.getCompletionFormID(), person, activity, false));
                } catch (Exception ignored) {}
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Метод отвечает за загрузку и отображение действий работы
     */
    private void getActions(String url) {
        actions = (LinearLayout) findViewById(R.id.info_work_actions);
        actions.removeAllViews();
        new SendGetRequest(url, person) {
            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    try {
                        workActions = RestClient.getGson().fromJson(result, WorkActionsItem[].class);
                        actions.setVisibility(View.GONE);
                        actions.removeAllViewsInLayout();
                        for (WorkActionsItem workAction : workActions) {
                            AButton action = new AButton(activity);
                            action.setText(workAction.getLabel());
                            action.setTag(workAction);
                            if (workAction.getColor().equals(ActivityConst.PREFERRED)) {
                                action.setBackground(AButton.GREEN);
                            } else {
                                action.setBackground(AButton.GRAY);
                            }
                            action.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    openActivity((WorkActionsItem) view.getTag());
                                }
                            });
                            actions.addView(action);
                        }
                        actions.setVisibility(View.VISIBLE);
                    } catch (Exception ignored) {
                    }
                } else if (Utils.checkSyncEnables(settings)) {
                    if (Utils.checkSyncEnables(settings)) {
                        WorkActionsTable workActionsTable = new WorkActionsTable(activity);
                        final List<WorkActionsItem> workActionItems = workActionsTable.get(work.getActionID());
                        if (!workActionItems.isEmpty()) {
                            for (WorkActionsItem button : workActionItems) {
                                AButton action = new AButton(activity);
                                action.setText(button.getLabel());
                                action.setTag(button);
                                if (button.getColor().equals(ActivityConst.PREFERRED)) {
                                    action.setBackground(AButton.GREEN);
                                } else {
                                    action.setBackground(AButton.GRAY);
                                }
                                action.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        openActivity((WorkActionsItem) view.getTag());
                                    }
                                });
                                actions.addView(action);
                            }
                            actions.setVisibility(View.VISIBLE);
                        } else {
                            actions.setVisibility(View.GONE);
                        }
                    }
                } else {
                    AppMsg.makeText(activity, getString(R.string.error_download_actions), AppMsg.STYLE_ALERT).show();
                }
                mainContent.setRefreshing(false);
                // получение списка подписей документа
                if (document != null) {
                    getSignList(document.getDocumentID());
                }
                super.onPostExecute(result);
            }
        }.execute();
    }

    /**
     * Действия с работой
     *
     * @param item - действие
     */
    private void openActivity(WorkActionsItem item) {
        // открываем активити отправки работы
        switch (item.getAction()) {
            case ActivityConst.SEND: {
                if (Utils.isOnline(activity, person.getHost())) {
                    switch (item.getOperation()) {
                        case ActivityConst.AGREEMENT: {
                            ActionUtils.sendWork(activity, person, work, document, ActionUtils.AGREEMENT,
                                    item.getAction(), item.getOperation());
                            break;
                        }
                        case ActivityConst.APPROVAL: {
                            ActionUtils.sendWork(activity, person, work, document, ActionUtils.APPROVAL,
                                    item.getAction(), item.getOperation());
                            break;
                        }
                        case ActivityConst.ACQUAINTANCE: {
                            ActionUtils.sendWork(activity, person, work, document, ActionUtils.ACQUAINTANCE,
                                    item.getAction(), item.getOperation());
                            break;
                        }
                    }
                }
                break;
            }
            case ActivityConst.TRANSMIT: {
                if (Utils.isOnline(activity, person.getHost())) {
                    Intent intent = new Intent(this, TransmitWorkActivity.class);
                    intent.putExtra(ActivityConst.PERSON, person);
                    intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                    intent.putExtra(ActivityConst.WORK_NAME, work.getName());
                    startActivityForResult(intent, ActionUtils.TRANSMIT_WORK);
                }
                break;
            }
            case ActivityConst.REASSIGN: {
                if (Utils.isOnline(activity, person.getHost())) {
                    Intent intent = new Intent(WorkInfoActivity.this, SendWorkActivity.class);
                    intent.putExtra(ActivityConst.PERSON, person);
                    if (work != null && work.getActionID() != null) {
                        intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                    } else {
                        intent.putExtra(ActivityConst.DOCUMENT_ID, document.getDocumentID());
                    }
                    intent.putExtra(ActivityConst.TYPE, ActionUtils.REASSIGN);
                    intent.putExtra(ActivityConst.FORM_ID, work.getCompletionFormID());
                    startActivityForResult(intent, ActionUtils.SEND_WORK);
                }
                break;
            }
            case ActivityConst.RESULT: {
                Intent intent = new Intent(this, ResultWorkActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                intent.putExtra(ActivityConst.WORK, work);
                startActivityForResult(intent, ActionUtils.REJECT_WORK);
                break;
            }
            case ActivityConst.COMPLETE: {
                switch (item.getOperation()) {
                    case ActivityConst.POINT_RESULT: {
                        // форма завершения файл
                        switch (formCompletion) {
                            case ActivityConst.FILE: {
                                ActionUtils.openActivityCompletionWorkFile(activity, person, work);
                                break;
                            }
                            case ActivityConst.COMMENT: {
                                ActionUtils.openActivityCompletionWorkComment(activity, person, work);
                                break;
                            }
                            case ActivityConst.FORM: {
                                if (!Utils.isOnline(getBaseContext(), person.getHost())) {
                                    return;
                                }
                                if (formCompletionDesc != null && formCompletionDesc.getPrevious_results() != null
                                        && formCompletionDesc.getPrevious_results().length != 0) {
                                    Intent intent1 = new Intent(activity, CompletionWorkFormActivity.class);
                                    intent1.putExtra(ActivityConst.PERSON, person);
                                    intent1.putExtra(ActivityConst.WORK_ID, work.getActionID());
                                    intent1.putExtra(ActivityConst.PREVIOUS_RESULTS, new ArrayList<>(Arrays.asList(formCompletionDesc.getPrevious_results())));
                                    startActivityForResult(intent1, ActionUtils.COMPLETION_WORK_FORM);
                                } else {
                                    ActionUtils.openActivityCompletionWorkForm(activity, person, work, formID, progressBar);
                                }
                                break;
                            }
                        }
                        break;
                    }
                    case ActivityConst.PROCESS: {
                        if (!person.getSettings().isEnableEDS() && person.getSettings().isNeedCert()) {
                            AppMsg.makeText(activity, getString(R.string.eds_not_installed_on_server), AppMsg.STYLE_ALERT).show();
                        } else {
                            Intent intent1 = new Intent(this, FinishProcessActivity.class);
                            intent1.putExtra(ActivityConst.PERSON, person);
                            intent1.putExtra(ActivityConst.WORK_NAME, work.getName());
                            intent1.putExtra(ActivityConst.WORK_ID, work.getActionID());
                            intent1.putExtra(ActivityConst.PROC_INST_ID, work.getProcInstID());
                            startActivityForResult(intent1, ActionUtils.PROCESS_FINISH_INFO);
                        }
                        break;
                    }
                    case ActivityConst.RESOLUTION_ACTION: {
                        Intent intent1 = new Intent(this, ActionResolutionActivity.class);
                        intent1.putExtra(ActivityConst.PERSON, person);
                        intent1.putExtra(ActivityConst.WORK_ID, work.getActionID());
                        startActivityForResult(intent1, ActionUtils.ACTION_RESOLUTION);
                        break;
                    }
                    case ActivityConst.PROGRESS: {
                        finishWorkDialog();
                        break;
                    }
                }
                break;
            }
            case ActivityConst.RESOLUTION: {
                if (Utils.isOnline(activity, person.getHost())) {
                    ActionUtils.checkSizeResolution(person, work.getActionID(), null, activity, progressBar);
                }
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            //UPD: 2023-05-31 - Добавлена проверка на null
            progressWork.setProgress(Integer.parseInt(String.valueOf(workPercent)));
            progressBar.setVisibility(View.GONE);
            return;
        }
        if (requestCode == ActionUtils.COMMENT) {
            getComments();
        } else if (requestCode == ActionUtils.ATTACHMENT) {
            getAttachments();
        } else if (requestCode == ActionUtils.PHOTO) {
            resultPhoto();
        } else if (requestCode == ActionUtils.TRANSMIT_WORK) {
            ActionUtils.updateWorkList(activity);
        } else if (requestCode == ActionUtils.COMPLETION_WORK_COMMENT) {
            completionWork(data);
        } else if (requestCode == ActionUtils.COMPLETION_WORK_FILE) {
            completionWork(data);
        } else if (requestCode == ActionUtils.COMPLETION_WORK_FORM) {
            completionWorkForm(data);
        } else if (requestCode == ActionUtils.REJECT_WORK) {
            rejectWork(data);
        } else if (requestCode == ActionUtils.PROCESS_FINISH_INFO) {
            completionProcess(data);
        } else if (requestCode == ActionUtils.SEND_WORK) {
            ActionUtils.updateWorkList(activity);
        } else if (requestCode == ActionUtils.ACTION_RESOLUTION) {
            ActionUtils.updateWorkList(activity);
        } else if (requestCode == ActionUtils.UPLOAD_FILE_FROM_STORAGE) {
            Node node = (Node) data.getSerializableExtra(FilesConst.NODE);
            if (node != null) {
                addFileFromStorage(node.getIdentifier(), UploadFile.INBOX_FILE);
            }
        }
    }

    /**
     * Метод вызывается при завершении работы с формой завершения форма
     *
     * @param data данные
     */
    private void completionWorkForm(Intent data) {
        // если завершается работа с перепорученными работами
        if (formCompletionDesc != null && formCompletionDesc.getPrevious_results().length > 0) {
            getFullData();
        } else {
            String fileUUID = data.getStringExtra(ActivityConst.FILE_IDENTIFIER);
            CompletionWorkForm completion = new CompletionWorkForm();
            completion.setActivity(activity);
            completion.setProgressBar(progressBar);
            completion.setPerson(person);
            completion.setFileIdentifier(fileUUID);
            completion.setWorkID(work.getActionID());
            completion.execute();
        }
    }

    /**
     * Метод используется для добавления нового файла в работу из хранилища
     *
     * @param uuid идентификатор файла
     */
    private void addFileFromStorage(final String uuid, final String container) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    AppMsg.makeText(activity, getString(R.string.error_to_copy_file), AppMsg.STYLE_ALERT).show();
                }
                try {
                    ErrorCode errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                    if (errorCode.getErrorCode().equals(Wrapper.ERROR)) {
                        AppMsg.makeText(activity, errorCode.getErrorMessage(), AppMsg.STYLE_ALERT).show();
                    } else if (errorCode.getErrorCode().equals(Wrapper.NO_ACCESS)) {
                        addFileFromStorage(uuid, UploadFile.WORK_FILE);
                    }
                } catch (Exception exc) {
                    getAttachments();
                }
                super.onPostExecute(result);
            }
            @Override
            protected String doInBackground(Void... voids) {
                try {
                    return new FilesManager(person).copy(RestClient.getGson().fromJson(new SendGetRequest(person).requestGET(person.getHost() +
                            "rest/api/workflow/work/" + work.getActionID() + "/document"), DocumentID.class).documentID, uuid, container);
                } catch (Exception exc) {
                    return null;
                }
            }
        }.execute();
    }

    /**
     * Метод вызывается при возвращении на текущий экран с экрана для добавления снимка с камеры
     */
    private void resultPhoto() {
        final String filePath = Environment.getExternalStorageDirectory() + File.separator +
                Const.DIRECTORY_PHOTOS_NAME + File.separator + photoFileName + Const.DEFAULT_FILE_FORMAT;
        final String fileName = Utils.getNewPhotoName(photoFileName, getBaseContext());
        // если есть подключение к интернету - добавляем файл
        if (Utils.isOnline(activity, person.getHost())) {
            AddFile addFile = new AddFile();
            addFile.setFileName(fileName);
            addFile.setFilePath(filePath);
            addFile.setWorkID(work.getActionID());
            addFile.execute();
        } else if (Utils.checkSyncEnables(settings)) {
            AddAttachment addAttachmentInTable = new AddAttachment(activity);
            addAttachmentInTable.add(work.getActionID(), filePath,
                    String.valueOf(System.currentTimeMillis()), work.getName(), fileName);
            // и обновляем вложения
            getAttachments();
        }
    }

    /**
     * Вызывается при возвращении из экрана для завершения работы с формой завершения
     *
     * @param data данные которые вернул экран
     */
    private void completionWork(Intent data) {
        // если онлайн
        if (Utils.isOnline(activity, person.getHost())) {
            findViewById(R.id.form_completion_panel).setVisibility(View.GONE);
            work = (WorkItem) data.getSerializableExtra(ActivityConst.WORK);
            getFullData();
        } else if (Utils.checkSyncEnables(settings)) {
            // получаем комментарий и имя файла
            String filename = data.getStringExtra(CompletionWorkFileActivity.FILENAME);
            String comment = data.getStringExtra(CompletionWorkCommentActivity.COMMENT);
            WorkActionsTable actions = new WorkActionsTable(activity);
            actions.removeByActionID(work.getActionID());
            if (filename != null) {
                WorkCommentsTable comments = new WorkCommentsTable(activity);
                comments.insertComment(work.getActionID(), person.getUserName(), filename,
                        String.valueOf(System.currentTimeMillis()), "comment_icon_result");
                FormCompletionTable forms = new FormCompletionTable(activity);
                forms.insertFormCompletion(work.getActionID(), ActivityConst.FILE, "true", "",
                        filename, String.valueOf(System.currentTimeMillis()), person.getUserName());
            } else if (comment != null) {
                WorkCommentsTable comments = new WorkCommentsTable(activity);
                comments.insertComment(work.getActionID(), person.getUserName(), comment,
                        String.valueOf(System.currentTimeMillis()), "comment_icon_result");
                FormCompletionTable forms = new FormCompletionTable(activity);
                forms.insertFormCompletion(work.getActionID(), ActivityConst.COMMENT, "false",
                        comment, "", String.valueOf(System.currentTimeMillis()), person.getUserName());
            }
            findViewById(R.id.form_completion_panel).setVisibility(View.GONE);
            work.setWork_state_label("progress");
            work.setWork_state_icon("progress_done_icon");
            work.setPercent("100");
            new WorksTable(activity).updateWork(work);
            getFullData();
        }
    }

    /**
     * Вызывается при возвращении из экрана для отклонения результата работы
     *
     * @param data данные которые вернул экран
     */
    private void rejectWork(Intent data) {
        // если работа подтверждена - сразу закрываем экран и обновляем список работ
        work = (WorkItem) data.getSerializableExtra(ActivityConst.WORK);
        if (work != null) {
            getFullData();
            return;
        }
        // если работа отклонена
        work = (WorkItem) data.getSerializableExtra(ActivityConst.REJECT_OFFLINE);
        if (work != null) {
            // скрытие блоков "Форма завершения"
            findViewById(R.id.work_info_completion_result_comment).setVisibility(View.GONE);
            findViewById(R.id.work_info_completion_result_file).setVisibility(View.GONE);
            // вставляем комментарий
            WorkCommentsTable comments = new WorkCommentsTable(activity);
            comments.insertComment(work.getActionID(), person.getUserName(), data.getStringExtra("comment"),
                    String.valueOf(System.currentTimeMillis()), "comment_icon_red");
            comments.removeCommentByIcon(work.getActionID());
            // добавляем форму завершения
            FormCompletionTable formsCompletion = new FormCompletionTable(activity);
            formsCompletion.addFormTypeWithRemove(work.getActionID());
            // обновляем кнопки в базе
            WorkActionsTable actions = new WorkActionsTable(activity);
            actions.removeByActionID(work.getActionID());
            // изменение типа текущей работы (т.к она стала звершенной)
            work.setWork_state_label("progress");
            work.setWork_state_icon("progress_status_icon");
            new WorksTable(activity).updateWork(work);
            getFullData();
        } else {
            work = (WorkItem) data.getSerializableExtra(ActivityConst.ACCEPT);
            if (work != null) {
                findViewById(R.id.form_completion_panel).setVisibility(View.GONE);
                work.setWork_state_label("progress");
                work.setWork_state_icon("progress_done_icon");
                work.setPercent("100");
                new WorksTable(activity).updateWork(work);
                getFullData();
            }
        }
    }

    /**
     * Вызывается при возвращении из экрана для завершения работы процессом
     *
     * @param data данные которые вернул экран
     */
    private void completionProcess(Intent data) {
        String type = data.getStringExtra("finished_send_work");
        String comment = data.getStringExtra("comment");
        if (type == null) {
            return;
        }
        if (statusWorkLabel.getText() != null) {
            if (type.equals("got_agree")) {
                if (statusWorkLabel.getText().equals(getString(R.string.on_agreement_full))) {
                    work.setWork_state_label("agreement");
                    work.setWork_state_icon("progress_done_icon");
                } else if (statusWorkLabel.getText().equals(getString(R.string.on_acquaintance_full))) {
                    work.setWork_state_label("acquaintance");
                    work.setWork_state_icon("progress_done_icon");
                } else if (statusWorkLabel.getText().equals(getString(R.string.on_approval_full))) {
                    work.setWork_state_label("approval");
                    work.setWork_state_icon("progress_done_icon");
                }
            } else {
                if (statusWorkLabel.getText().equals(getString(R.string.on_agreement_full))) {
                    work.setWork_state_label("agreement");
                    work.setWork_state_icon("progress_denied_icon");
                } else if (statusWorkLabel.getText().equals(getString(R.string.on_approval_full))) {
                    work.setWork_state_label("approval");
                    work.setWork_state_icon("progress_denied_icon");
                }
            }
            work.setStateID("1");
        }
        if (!Utils.isOnline(activity, person.getHost()) && Utils.checkSyncEnables(settings)) {
            WorkActionsTable actions = new WorkActionsTable(activity);
            actions.removeByActionID(work.getActionID());
            if (comment != null && comment.length() != 0) {
                String icon;
                if (type.equals("got_agree")) {
                    icon = "comment_icon_green";
                } else {
                    icon = "comment_icon_red";
                }
                WorkCommentsTable comments = new WorkCommentsTable(activity);
                comments.insertComment(work.getActionID(), person.getUserName(), comment,
                        String.valueOf(System.currentTimeMillis()), icon);
                new WorksTable(activity).updateWork(work);
            }
        }
        // обновляем экран
        getFullData();
    }

    /**
     * Клик на кнопку "Назад"
     */
    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(ActivityConst.WORK, work);
        setResult(RESULT_OK, intent);
        finish();

    }

    /**
     * Метод для обновления списка вложений
     */
    private void getAttachments() {
        new AttachmentList(activity, person, work, progressBar).execute();
    }

    /**
     * Метод для обновления списка комментариев
     */
    private void getComments() {
        new CommentsList(activity, person, work, workButton, documentButton, personalButton).execute();
    }

    /**
     * Диалог изменения прогресса
     */
    private void changeProgressDialog() {
        AlertDialog.Builder adb = new AlertDialog.Builder(activity);
        adb.setTitle(getString(R.string.change_progress_title));
        adb.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                changeProgress(progressWork.getProgress());
            }
        });
        adb.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                progressWork.setProgress(workPercent);
            }
        });
        adb.setMessage(getString(R.string.change_progress_answer));
        adb.show();
    }

    /**
     * Диалог завершения работы
     */
    private void finishWorkDialog() {
        AlertDialog.Builder adb = new AlertDialog.Builder(activity);
        adb.setTitle(getString(R.string.finish_work_title));
        adb.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                changeProgress(100);
            }
        });
        adb.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                progressWork.setProgress(workPercent);
            }
        });
        adb.setMessage(getString(R.string.finish_work_answer));
        adb.show();
    }

    /**
     * Класс отвечает за изменение прогресса работы, либо ее завершение
     * Если прогресс равен 100 - закрываем активити и обновляем список с работами
     */

    private void changeProgress(final int progress) {
        new SendGetRequest("rest/api/workflow/work/set_progress?workID=" + work.getActionID() +
                "&progress=" + progress + "&locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    ErrorCode errorCode;
                    try {
                        errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                    } catch (JsonSyntaxException exc) {
                        errorCode = null;
                    }
                    if (errorCode != null) {
                        if (errorCode.getErrorCode().equals(Wrapper.NO_ERROR)) {
                            if (progress == 100) {
                                ActionUtils.updateWorkList(activity);
                            } else {
                                work.setPercent(String.valueOf(progress));
                            }
                        } else {
                            AppMsg.makeText(activity, errorCode.getErrorMessage(), AppMsg.STYLE_ALERT).show();
                        }
                    }
                } else if (Utils.checkSyncEnables(settings)) {
                    AddChangeProgress cProgress = new AddChangeProgress(activity);
                    cProgress.add(work.getActionID(), progress, work.getName());
                    if (progress == 100) {
                        work.setPercent("100");
                        Intent intent = new Intent();
                        intent.putExtra(ActivityConst.WORK, work);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        work.setPercent(String.valueOf(progress));
                    }
                } else {
                    AppMsg.makeText(activity, getString(R.string.error_change_progress), AppMsg.STYLE_ALERT).show();
                }
                progressBar.setVisibility(View.GONE);
                super.onPostExecute(result);
            }
        }.execute();
    }

    class DocumentID {
        String documentID;
    }

    /**
     * Класс отвечает за добавление файла к работе
     */
    class AddFile extends AsyncTask<Void, Void, String> {

        String filePath;
        String fileName;
        String workID;

        public void setWorkID(String workID) {
            this.workID = workID;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        @Override
        protected void onPreExecute() {
            if (addFileProgress == null) {
                addFileProgress = new ProgressDialog(activity);
                addFileProgress.setMessage(getString(R.string.please_wait));
                addFileProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                addFileProgress.setCancelable(false);
            }
            addFileProgress.show();
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                ErrorCode errorCode;
                try {
                    errorCode = RestClient.getGson().fromJson(result, ErrorCode.class);
                } catch (JsonSyntaxException exc) {
                    errorCode = null;
                }
                if (errorCode != null) {
                    if (!errorCode.getResult().equals(Wrapper.NO_ERROR)) {
                        AppMsg.makeText(activity, errorCode.getMessage(), AppMsg.STYLE_ALERT).show();
                    }
                    getAttachments();
                    getActions();
                }
            } else {
                AppMsg.makeText(activity, getString(R.string.error_add_file), AppMsg.STYLE_ALERT).show();
            }
            addFileProgress.dismiss();
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            UploadFile uploadFile = new UploadFile(person, false, UploadFile.INBOX_FILE);
            try {
                return uploadFile.uploadFile(workID, fileName, filePath, true);
            } catch (Exception exc) {
                return null;
            }
        }
    }
}