BemsWebApplication.Announce = function (params, viewInfo) {
    'use strict';

    var imagefileUrl1 = ko.observable(),
        uploadedFileInfo = {},
        dropZone1 = null;

    var eq = BWA.DataUtil.constructEqualFilter,
        and = BWA.DataUtil.andFilter;

    var partnerTypeDataSource = BemsWebApplication.db.createDataSource('CmPartnerType', false, true, true),
         partnerDataSource = BemsWebApplication.db.createDataSource('CmPartner', true, true, true),
        contractClassDataSource = BemsWebApplication.db.createDataSource('FmsContractClass', true, true, true),
        contractMethodDataSource = BemsWebApplication.db.createDataSource('FmsContractMethod', true, true, true),
        contractTypeDataSource = BemsWebApplication.db.createDataSource('FmsContractType', true, true, true),
        paymentTypeDataSource = BemsWebApplication.db.createDataSource('FmsPaymentType', true, true, true),

        businessFieldDataSource = BemsWebApplication.db.createDataSource('CmBusinessField', true, true, true);

    var businessFieldsForSearch = ko.observableArray();

    var partnerTypes = ko.observableArray(),
        contractClasses = ko.observableArray(),
        contractMethods = ko.observableArray(),
        contractTypes = ko.observableArray(),
        paymentTypes = ko.observableArray(),
        allPartner = ko.observableArray(),
        filteredPartner = ko.observableArray(),

        businessFields = ko.observableArray();

    var partnerTypesForSearch = ko.observableArray(),
        contractClassesForSearch = ko.observableArray(),
        contractMethodsForSearch = ko.observableArray(),
        contractTypesForSearch = ko.observableArray(),
        paymentTypesForSearch = ko.observableArray();

    var deferredForSearch = new $.Deferred();

    var now = new Date();
    var endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);

    var eq = BWA.DataUtil.constructEqualFilter;

    var dataSourceOptions = {
        select: [
            'SiteId',
            'AnnouncementId',
            'BusinessFieldId',
            'CmBusinessField/Name',
            'Title',
            'Contents',
            'RegisterUserId ',
            'CmUser/Name', // 등록자
            'FileId',
            'CmFile/Name',
            'CmFile/FileSize',
            'AddDate',
            'UpdateDate',
            'IsUse',
            'ReadCount',
        ],
        expand: [
            'CmBusinessField',
            'CmFile',
            'CmUser'
        ],

        extendOptions: {
            forceOriginalField: true
        },
        filter: [
            ['SiteId', '=', BWA.UserInfo.SiteId()],
            'and',
            ['UpdateDate', '>', endDate]
        ]
    };
    var viewModel = BWA.DataGrid.createViewWithDataGrid(params, viewInfo, 'CmAnnouncement', {
        dataSourceOptions: dataSourceOptions,
        columns: [
            { dataField: 'AnnouncementId', caption: $G('number'), width: '10%', alignment: 'center', allowFiltering: false, sortOrder: 'desc' },
            { dataField: 'CmBusinessField/Name', caption: '업무분야', width: '10%', alignment: 'center' },
            { dataField: 'Title', caption: '제목', width: '40%', alignment: 'center' },
            { dataField: 'CmUser/Name', caption: '등록자', width: '20%', alignment: 'center' },
            {
                dataField: 'AddDate', caption: '등록일', width: '20%', alignment: 'center', dataType: "shortDate", format: "yyyy-MM-dd",
                customizeText: function (cellInfo) {
                    return cellInfo.valueText;
                }
            },
            {
                dataField: 'UpdateDate', caption: '만료일', width: '20%', alignment: 'center', dataType: "shortDate", format: "yyyy-MM-dd",
                customizeText: function (cellInfo) {
                    return cellInfo.valueText;
                }
            },
            //utils.datagrid.columnIsUse('20%')
            { dataField: 'ReadCount', caption: '조회수', width: '10%', alignment: 'center' },
        ],
        paging: {
            pageSize: 18,
            enabled: true
        },
        pager: {},

        // 2019.04.17 엑셀 출력 기능 추가 ~~~
        "export": {
            enabled: true,
            fileName: '공지사항 목록'
        },
        onExporting: function (e) {
            e.component.columnOption('AnnouncementId', "visible", false);
        },
        onExported: function (e) {
            e.component.columnOption('AnnouncementId', "visible", true);
        },
        // ~~~ 2019.04.17 엑셀 출력 기능 추가

        //popupWidth: 580,
        searchViewItems: [
            { id: 'BusinessFieldId', ignoreValue: 0, defaultValue: 0, dataSource: businessFieldsForSearch },
            { id: 'Title' },
            { id: 'Contents' },
            { id: 'AddDate', type: 'dateRange', isOnlyDate: true },
        ],

        handleAfterLoadingModelByKey: function (data, dataViewModel, isNewInPopup) {

            if (isNewInPopup() == false) {

                if (_.isNull(dataViewModel.FileId()) === false) {
                    imagefileUrl1('{0}/CmFile(SiteId={1},FileId={2})/$value'.formati(BWA.db._url, dataViewModel.SiteId(), dataViewModel.FileId()));
                }
                else {
                    imagefileUrl1(undefined);
                }

                var keys = BWA.db.extractKeysObject('CmAnnouncement', dataViewModel);
                dataViewModel.ReadCount(dataViewModel.ReadCount() + 1);
                BWA.db.CmAnnouncement.update(keys, dataViewModel.toJS());
            }

            // 작업지시 세부 내용은 수정/삭제 할 수 없음 
            viewModel.visibleEditButton(false);
            viewModel.visibleDeleteButton(false);
        },

        handleDataGridRowClick: function (id, dataGrid, clickRow, popupVisible) {

            dataGrid.clearSelection();

            var data = clickRow.data;
            var dataModel = viewModel.dataModel;

            if (data['FileId']() != null)
                dataModel.AttachmentFileName(data['CmFile/Name']());
            else dataModel.AttachmentFileName('');

            popupVisible(true);
        },

        handleViewShowing: function (dataModel) {
            var useBusinessFiltering = BWA.UserInfo.isDependBusinessField(viewInfo.viewName);
            if (useBusinessFiltering) {
                dataSourceOptions.filter.push('and');
                dataSourceOptions.filter.push([eq('BusinessFieldId', BWA.UserInfo.BusinessFieldId()), 'or', eq('BusinessFieldId', 1)]);

                businessFieldDataSource.filter([
                  eq('SiteId', BWA.UserInfo.SiteId()),
                  and,
                  [eq('BusinessFieldId', BWA.UserInfo.BusinessFieldId()), 'or', eq('BusinessFieldId', 1)]
                ]);
            }
            businessFieldDataSource.load().done(function (dbBusinessFields) {
                businessFields(dbBusinessFields);

                businessFieldsForSearch($SearchView.createArrayOfSelectBox('BusinessFieldId', businessFields()));
            });


            //$.when(
            //    partnerTypeDataSource.load(),
            //    contractClassDataSource.load(),
            //    contractMethodDataSource.load(),
            //    contractTypeDataSource.load(),
            //    paymentTypeDataSource.load(),
            //    partnerDataSource.load()
            //).done(function (partnerTypeDataResult, contractClassDataResult, contractMethodDataResult, contractTypeDataResult, paymentTypeDataResult, partnerDataResult) {
            //    partnerTypes(partnerTypeDataResult[0]);
            //    contractClasses(contractClassDataResult[0]);
            //    contractMethods(contractMethodDataResult[0]);
            //    contractTypes(contractTypeDataResult[0]);
            //    paymentTypes(paymentTypeDataResult[0]);
            //    allPartner(partnerDataResult[0]);

            //partnerTypesForSearch($SearchView.createArrayOfSelectBox('PartnerTypeId', partnerTypeDataResult[0]));
            //contractClassesForSearch($SearchView.createArrayOfSelectBox('ContractClassId', contractClassDataResult[0]));
            //contractMethodsForSearch($SearchView.createArrayOfSelectBox('ContractMethodId', contractMethodDataResult[0]));
            //contractTypesForSearch($SearchView.createArrayOfSelectBox('ContractTypeId', contractTypeDataResult[0]));
            //paymentTypesForSearch($SearchView.createArrayOfSelectBox('PaymentTypeId', paymentTypeDataResult[0]));

            //deferredForSearch.resolve();
            //});
        },
        handlePopupShowing: function (isNewInPopup, dataViewModel) {
            // 신규등록인 경우 
            if (isNewInPopup()) {
                dataViewModel.AddDate(new Date());
                dataViewModel.UpdateDate(new Date());
                dataViewModel.RegisterUserId(BWA.UserInfo.UserId());
            }
        },

        handlePopupShown: function (isEditMode, isNew, dataViewModel) {

        },

        handleViewShown: function (dataViewModel, isEditModeInPopup) {
            setupDropZone(isEditModeInPopup, dataViewModel);
        },

        handleSaveSuccess: function () {
            if (_.isNull(dropZone1) === false) {
                dropZone1.resetUploadedFileInfo();
            }
        },
    });

    function processValueChange(e) {

        filteredPartner([]);

        _.each(allPartner(), function (partner) {
            if (e.value === partner.PartnerTypeId()) {
                filteredPartner.push(partner);
            }
        });

        if (!_.isEmpty(filteredPartner())) {
            viewModel.dataModel.PartnerId(filteredPartner()[0].PartnerId());
        }
    }

    function setupDropZone(isEditModeInPopup, dataViewModel) {

        var timer = null;
        isEditModeInPopup.subscribe(function (value) {

            if (value) {

                if (timer) { clearInterval(timer); }

                timer = setInterval(function () {

                    if ($('#announcementDropZone1').length) {

                        if (_.isNull(dropZone1)) {

                            dropZone1 = BWA.DropZone.create({

                                id: '#announcementDropZone1',

                                categoryId: $Code.FileCategory.ANNOUNCEMENT,
                                uploadedFileInfo: uploadedFileInfo,
                                handleRemoveBeforePromise: function () {

                                    var keys = BWA.db.extractKeysObject('CmAnnouncement', dataViewModel);
                                    return BWA.db.CmAnnouncement.update(keys, { FileId: null });
                                },
                                handleSuccess: function (fileInfo) {
                                    dataViewModel.FileId(fileInfo.FileId);
                                },

                                handleRemovedFile: function () {
                                    dataViewModel.FileId(null);
                                },
                            });

                            uploadedFileInfo.SiteId = dataViewModel.SiteId();
                            uploadedFileInfo.FileId = dataViewModel.FileId();

                            if (uploadedFileInfo.FileId) {

                                BWA.db.CmFile.byKey(uploadedFileInfo).done(function (data) {

                                    dropZone1.removeAllFiles();

                                    dropZone1.emit('addedfile', {
                                        name: data.Name,
                                        size: data.FileSize
                                    });
                                    //dropZone.options.maxFiles = 0; // 이게 있으면 삭제후 다시 업로드가 안 된다.
                                });
                            }
                        }
                    }

                }, 100);
            }
            else {
                if (timer) { clearInterval(timer); timer = null; }
                dropZone1 = null;
            }
        });
    }

    viewModel.popupVisible.subscribe(function (value) {
        if (!value) {
            viewModel.gridView().refresh();
        }
    });

    viewModel.dataModel.AttachmentFileName = ko.observable();
    viewModel.imagefileUrl1 = imagefileUrl1;

    viewModel.businessFields = businessFields;

    viewModel.processValueChange = processValueChange;
    viewModel.partnerTypes = partnerTypes;
    viewModel.contractClasses = contractClasses;
    viewModel.contractMethods = contractMethods;
    viewModel.contractTypes = contractTypes;
    viewModel.paymentTypes = paymentTypes;
    viewModel.allPartner = allPartner;
    viewModel.filteredPartner = filteredPartner;

    return viewModel;
};