$(function () {
    "use strict";
    var TEXTAREA_HEIGHT_MAX = 420,
        TEXTAREA_HEIGHT_MIN = 240;

    var dropZone = null;
    var historyViewModel = new BemsWebApplication.FmsDrawingHistoryViewModel();
    
    var uploadedFileInfo = {};
    //2019-11-25 변경
    var backUpFileId = null;
    var eq = BWA.DataUtil.constructEqualFilter;
    var and = BWA.DataUtil.andFilter;
    var drawingHistoryDataSource = BemsWebApplication.DataUtil.createDataSource({
        dataSourceOptions: {
            select: [
                'SiteId', 'DrawingId', 'HistoryId', 'FileId', 'Description', 'RevisionNo',
                'UpdatedDate', 'UpdatedUserId',
                'CmFile/Name', 'CmFile/FileSize', 'CmUser/Name'
            ],
            expand: ['CmFile', 'CmUser'],
            extendOptions: {
                forceOriginalField: true
            }
        }

    }, 'FmsDrawingHistory');
    //2019-11-25 변경
    BWA.Popup = BWA.Popup || {};
    BWA.Popup.DrawingHistory = {

        create: function (viewModel, params, drawingHistories, reloadDrawingHistory) {

            // 다운로드 기능은 다른 창으로 url를 열면 될 듯하다.
            var drawingId = viewModel.dataModel.DrawingId,

            // hcLee 2016 03 28
//                textAreaHeightInPopup = ko.observable(),

            popupVisible = ko.observable(false),
            position = ko.observable(),
            isNewData = ko.observable(false),

            IsPrevImg = ko.observable(false),
            RowHistoryId = null,
//                textAreaHistoryNoteHeight = ko.observable(TEXTAREA_HEIGHT_MAX),

            uploadedFileInfo = {},
            isVisibleDropZone = ko.observable('hidden'),

            isEditMode = ko.observable(false),
            //isVisibleDeleteButton = ko.observable(true),
            isVisibleSaveButton = ko.observable(false),
            isVisibleCancelButton = ko.observable(true),
            isVisibleEditButton = ko.observable(true),

            selectedHistory = null,
            historyGridView = null,
            timerObj = { timer: null },
            mainPopupElement = params.mainPopupElement;

            historyViewModel.UpdatedUserName = ko.observable();
            historyViewModel.FileName = ko.observable();
            //hcLee 2016 03 28
            historyViewModel.FildIdBackUp = ko.observable();

            BWA.db.FmsDrawingHistory.modified.add(function () {
                reloadDrawingHistory(drawingId());
                $('#gridContainer').dxDataGrid('instance').refresh();
            });

            function handleButtonSave() {
                historyViewModel.SiteId(BWA.UserInfo.SiteId());
                historyViewModel.DrawingId(drawingId());
                if (isNewData()) {
                    if (drawingHistoryFileUpload.dropzone.files.length == 0) {
                        utils.toast.show('도면 파일을 업로드하여 주십시오.', 'error');
                        return;
                    }

                    //2019-11-25 변경
                    if (_.isNull(dropZone) === false) { //추가
                        if (historyViewModel.FileId() == null) {
                            dropZone.processQueue();
                        }
                    }
                    //2019-11-25 변경

                    historyViewModel.UpdatedDate(new Date());
                    historyViewModel.UpdatedUserId(BWA.UserInfo.UserId());
                    
                    BWA.db.FmsDrawingHistory.insert(historyViewModel.toJS()).done(function (res) {
                        utils.toast.show('도면 이력 항목이 성공적으로 저장되었습니다.');
                        dropZone.resetUploadedFileInfo();
                        // 2016 03 28
                        reloadDrawingHistory(drawingId());
                        $('#gridContainer').dxDataGrid('instance').refresh();
                        isNewData(false);
                        ChangeMode(false);

                        popupVisible(false);
                        IsPrevImg(false);
                    });

                }
                else {
                    // hcLee 2016 03 27
                    if (_.isUndefined(historyViewModel.FileId()) || historyViewModel.FileId() == null) {

                        utils.toast.show('도면 파일을 업로드하여 주십시오.', 'error');
                        return;
                    }

                    historyViewModel.RevisionNo(undefined);
                    //historyViewModel.FileId(undefined); // hcLee 2016 03 28
                    historyViewModel.UpdatedDate(new Date());
                    historyViewModel.UpdatedUserId(BWA.UserInfo.UserId());

                    //2019-11-25 변경
                    backUpFileId = historyViewModel.FileId();
                    if (_.isNull(dropZone) === false) {
                            dropZone.processQueue();
                    }
                    //2019-11-25 변경
                    var keys = BWA.db.extractKeysObject('FmsDrawingHistory', historyViewModel);
                    BWA.db.FmsDrawingHistory.update(keys, historyViewModel.toJS()).done(function (res) {
                        utils.toast.show('도면 이력 항목이 성공적으로 저장되었습니다.');
                        dropZone.resetUploadedFileInfo();
                        reloadDrawingHistory(drawingId());
                        $('#gridContainer').dxDataGrid('instance').refresh();
                        ChangeMode(false);
                        popupVisible(false);
                        IsPrevImg(true);
                    });
                    
                }
            }
            /*
            function handleButtonDelete() {

                var keys = BWA.db.extractKeysObject('FmsDrawingHistory', historyViewModel);

                BWA.db.FmsDrawingHistory.remove(keys).done(function() {
                    BWA.db.CmFile.remove({
                        SiteId: historyViewModel.SiteId(),
                        FileId: historyViewModel.FileId()

                    }).done(function() {

                        utils.toast.show('도면 이력 항목 삭제 처리가 성공하였습니다.');
                        popupVisible(false);
                    });
                });
            }*/
            function ChangeMode(bEdit) {
                if (bEdit) {
                    setupDropzone(bEdit); // 업로드된 파일을 지운후 저장하지 않고 취소만 하고 다시 수정을 시작한 경우를 위하여 hcLee 2016 03 25
                    isEditMode(true);

                    isVisibleEditButton(false);
                    isVisibleSaveButton(true);
                    isVisibleCancelButton(true);
                }
                else {
                    setupDropzone(false); // 업로드된 파일을 지운후 저장하지 않고 취소만 하고 다시 수정을 시작한 경우를 위하여 hcLee 2016 03 25
                    isEditMode(false);

                    isVisibleEditButton(true);
                    isVisibleSaveButton(false);
                    isVisibleCancelButton(false);
                }
            }

            function handleEditDrawingHistory() {
                ChangeMode(true);
            }


            function setupDropzone(bEdit) {
                //var clone2 = $("div.dz-preview").clone(); // making zeh' clones!

                if (bEdit) {

                    if (dropZone) {
                        dropZone.removeAllFiles();
                        dropZone.options.startLoadFileCount = 0;

                        $('div.dz-preview').remove();
                    }

                    historyViewModel.FileId(historyViewModel.FildIdBackUp()); // hcLee 2016 03 25
                    if (_.isNull(dropZone)) {
                        dropZone = BWA.DropZone.create({
                            id: '#drawingHistoryFileUpload',
                            categoryId: $Code.FileCategory.DRAWING,
                            uploadedFileInfo: uploadedFileInfo,
                            previewTemplate: "...",

                            handleSuccess: function (fileInfo) {
                                //2019-11-25 변경
                                historyViewModel.FileId(fileInfo.FileId);
                                var tempFileID = fileInfo.FileId;
                                if (uploadedFileInfo.FileId) {
                                    drawingHistoryDataSource.filter([
                                        eq('SiteId', BWA.UserInfo.SiteId()),
                                        and,
                                        eq('DrawingId', historyViewModel.DrawingId())
                                    ]);
                                    drawingHistoryDataSource.load().done(function (histories) {
                                        drawingHistories(histories);
                                        var len = drawingHistories().length;
                                        if (RowHistoryId != null)
                                            historyViewModel.HistoryId(RowHistoryId);
                                        else
                                            historyViewModel.HistoryId(drawingHistories()[len - 1].HistoryId());

                                        var keys = BWA.db.extractKeysObject('FmsDrawingHistory', historyViewModel);
                                        if (keys.HistoryId != null) {
                                            return BWA.db.FmsDrawingHistory.update(keys, { FileId: tempFileID })
                                                .done(function (res) {
                                                    $('#gridContainer').dxDataGrid('instance').refresh();
                                                    if (IsPrevImg() == true) { // 그림삭제
                                                        var temp = {
                                                            SiteId: BWA.UserInfo.SiteId(),
                                                            FileId: backUpFileId
                                                        }
                                                        BWA.db.CmFile.byKey(temp).done(function (data) {
                                                            dropZone.removeFile(data);
                                                        });
                                                    }
                                                });
                                            if (fileInfo.FileId != null)
                                                IsPrevImg(true);
                                            else
                                                IsPrevImg(false);
                                        }
                                    });
                                }
                            },
                            handleRemovedFile: function () {
                                historyViewModel.FileId(null);
                            },
                        });
                    }
                }
            }
            popupVisible.subscribe(utils.popup.getAttachFunc('#popupDetail', timerObj, position));

            position.subscribe(function (value) {

            });

            isNewData.subscribe(function (isNew) {
                if (isNew && popupVisible()) {

                    isVisibleDropZone('visible');
                }
                else {

                    isVisibleDropZone('hidden');
                }
            });

            viewModel.popupVisible.subscribe(function (value) {

                if (value === false) {
                    popupVisible(false);
                }

            });

            viewModel.isEditModeInPopup.subscribe(function (value) {

            });


            return {
                visible: popupVisible,
                isNewData: isNewData,
                dataModel: historyViewModel,
                isVisibleDropZone: isVisibleDropZone,
                isEditMode: isEditMode,

                show: function () {

                    popupVisible(true);
                },

                hide: function () {

                    popupVisible(false);
                },

                popupOptions: {
                    width: '480px',
                    height: '616px',
                    dragEnabled: false,

                    position: position,
                    visible: popupVisible,
                    showingAction: function () { },
                    closeOnOutsideClick: false,
                    shading: false,

                    animation: {
                        show: { type: "slide", duration: 150, from: { left: '-=10', opacity: 0 }, to: { opacity: 1 } },
                        hide: { type: "slide", duration: 150, from: { left: '-=10', opacity: 1 }, to: { opacity: 0 } }
                    },

                    shownAction: function () {

                        if (isNewData()) {
                            isVisibleDropZone('visible');
                        }
                        else {
                            isVisibleDropZone('hidden');
                        }
                        setupDropzone();
                    },

                    hidingAction: function () {
                        //dropZone.dispose(uploadedFileInfo); // 2016 03 29
                    }

                },

                toolbarItems: [
                    { location: 'before', text: $G('drawingHistoryDetailInfo') },
                    {
                        location: 'after',
                        widget: 'button',
                        options: {
                            text: '수정',
                            icon: 'edit',
                            visible: isVisibleEditButton,
                            disabled: viewModel.hasnotModificationPermission,
                            clickAction: handleEditDrawingHistory
                        }
                    },
                    {
                        location: 'after',
                        widget: 'button',
                        options: {
                            text: '취소',
                            icon: 'cancel',
                            visible: isVisibleCancelButton,
                            disabled: viewModel.hasnotModificationPermission,
                            clickAction: function () {
                                // 파일 id를 다시 설정해야 한다. hcLee 2016 03 25
                                historyViewModel.FileId(historyViewModel.FildIdBackUp()); // hcLee 2016 03 25
                                ChangeMode(false);
                            }
                        }
                    },
                    {
                        location: 'after', widget: 'button', options: {
                            text: $G('save'),
                            icon: 'save',
                            visible: isVisibleSaveButton,
                            disabled: viewModel.hasnotModificationPermission,
                            clickAction: handleButtonSave
                        }
                    },
                    {
                        location: 'after', widget: 'button', options: {
                            text: $G('close'),
                            icon: 'close',
                            clickAction: function () {
                                isNewData(false);
                                ChangeMode(false);
                                popupVisible(false);
                            }
                        }
                    }
                ],

                setDrawingHistoryGridViewInstance: function (instance) {
                    historyGridView = instance;
                },

                setSelectedDrawingHistory: function (history) {
                    isNewData(false);

                    BWA.DataUtil.copyViewModel(history, historyViewModel);

                    RowHistoryId = history.HistoryId();

                    historyViewModel.FildIdBackUp(history.FileId()); // hcLee 2016 03 28                    
                    historyViewModel.FileName(history['CmFile/Name']());
                    historyViewModel.UpdatedUserName(history['CmUser/Name']());
                    historyViewModel.Description(history['Description']());

                    ChangeMode(false);
                },

                handleInsertDrawingHistory: function () {
                    ChangeMode(false);
                    popupVisible(false);

                    isNewData(true);
                    BWA.DataUtil.resetDataModel(_.omit(historyViewModel, 'DrawingId'));

                    var maxHistory = _.max(drawingHistories(), function (x) {
                        return x.RevisionNo();
                    });

                    historyViewModel.RevisionNo(maxHistory.RevisionNo() + 1);

                    historyViewModel.UpdatedUserName(BWA.UserInfo.Name());

                    popupVisible(true);
                    ChangeMode(true);
                    isVisibleCancelButton(false);
                }
            };
        }
    }
});