BemsWebApplication.CivilComplaint = function (params, viewInfo, executionPlanOptions) {
    "use strict";

    var businessFieldDataSource = BemsWebApplication.db.createDataSource('CmBusinessField', true, true, true),
        workTypeDataSource = BemsWebApplication.db.createDataSource('FmsWorkCodeType'),
        progressDataSource = BemsWebApplication.db.createDataSource('FmsWorkCodeProgress'),
        businessFields = ko.observableArray(),
        workTypes = ko.observableArray(),
        progresses = ko.observableArray();
    var deferredForSearch = new $.Deferred();

    var workTypesForSearch = ko.observableArray(),
        businessFieldsForSearch = ko.observableArray(),
        progressesForSearch = ko.observableArray();
    var SiteId = BWA.UserInfo.SiteId();
    var popup;

    var eq = BWA.DataUtil.constructEqualFilter,
        and = BWA.DataUtil.andFilter,
        or = BWA.DataUtil.orFilter,
        noteq = BWA.DataUtil.constructNotEqualFilter;

    var workTypeId = $Code.WorkType.CIVIL_COMPLAINT;
    var executionPlanViewOptions = undefined,
        executionPlanPopupOptions = undefined;

    if (executionPlanOptions) {
        executionPlanViewOptions = executionPlanOptions.viewOptions;
        executionPlanPopupOptions = executionPlanOptions.popupOptions;
    }

    var selectedFacilityData = ko.observable(),
        selectedUserData = params.selectedUserData || ko.observable();

    var dataSourceOptions = {

        select: [
            'SiteId', 'WorkRequestId', 'WorkTypeId', 'Title', 'RequestDate', 'WorkProgressId', 'StartWorkDate',
            'CmUser/Name', // 신청자
            'CmUser1/Name', // 반려자
            'FmsWorkCodeType/Name', 'CmBusinessField/Name', 'FmsWorkCodeProgress/Name',
            'FmsWorkSchedule/IsUse'
        ],
        expand: ['FmsWorkCodeType', 'CmBusinessField', 'FmsWorkCodeProgress', 'CmUser', 'CmUser1', 'FmsWorkSchedule'],
        extendOptions: {
            forceOriginalField: true
        }
    };

    if (_.isUndefined(executionPlanViewOptions)) {
        dataSourceOptions.filter = [
            eq('SiteId', SiteId),
            and,
            eq('WorkTypeId', $Code.WorkType.CIVIL_COMPLAINT)
        ];
    }
    else {
        // 시설관리 > 실행계획조회 화면에서는 작업계획 상태만 가져옴 
        dataSourceOptions.filter = [
            eq('SiteId', SiteId),
            and,
            eq('WorkProgressId', $Code.WorkProgress.WORK_PLAN),
            and,
            [("WorkTypeId", "<=", $Code.WorkType.LEGAL_CHECK, and, eq('FmsWorkSchedule/IsUse', true)),
            or,
            ["WorkTypeId", ">", $Code.WorkType.LEGAL_CHECK]]
        ];
    }

    var viewModel = BWA.DataGrid.createViewWithDataGrid(params, viewInfo, 'FmsWorkRequest', {
        popupWidth: 1200,
        dataSourceOptions: dataSourceOptions,
        columns: [
            { dataField: 'WorkRequestId', caption: $G('number'), width: '8%', alignment: 'center' },
            { dataField: 'CmBusinessField/Name', caption: $G('businessFieldName'), width: '10%', alignment: 'center' },
            { dataField: 'FmsWorkCodeProgress/Name', caption: $G('workProgressName'), width: '10%', alignment: 'center', visible: false },
            { dataField: 'FmsWorkCodeType/Name', caption: $G('workTypeName'), width: '10%', alignment: 'center' },
            { dataField: 'Title', caption: '작업명', width: '45%', alignment: 'center' },
            {
                dataField: 'StartWorkDate', caption: '작업예정일', width: '12%', alignment: 'center', sortOrder: 'asc',
                customizeText: function (cellInfo) {
                    return $G.date(cellInfo.value);
                }
            },
            { dataField: 'CmUser/Name', caption: $G('requesterName'), width: '15%', alignment: 'center' }
        ],
        promiseDataInSearchView: deferredForSearch.promise(),
        searchViewItems: _.compact([

            { id: 'WorkProgressId', ignoreValue: 0, defaultValue: 0, dataSource: progressesForSearch },
            { id: 'WorkTypeId', ignoreValue: 0, defaultValue: 0, dataSource: workTypesForSearch },
            { id: 'Title' },
            { id: 'CmUser/Name' },
            { id: 'BusinessFieldId', ignoreValue: 0, defaultValue: 0, dataSource: businessFieldsForSearch },
            { id: 'StartWorkDate', type: 'dateRange', isOnlyDate: true }
        ]),

        handleDataGridRowClick: function (id, dataGrid, clickRow, popupVisible) {
            dataGrid.clearSelection();
            var data = clickRow.data;
            var dataModel = viewModel.dataModel;

            // 정기, 법정인 경우는 반려가 안보이게  2016 06 16 hcLee
            if (!_.isUndefined(viewModel.executionPlanPopupOptions)) {
                if (data.WorkTypeId() < 3)
                    viewModel.executionPlanPopupOptions.isVisibleRejectButtons(false);
                else
                    viewModel.executionPlanPopupOptions.isVisibleRejectButtons(true);
            }
            if (popup && popup.handleBeforeShowingPopupForEdit) {
                popup.handleBeforeShowingPopupForEdit(data, dataModel);
            }
            popupVisible(true);
        },

        handleBeforePopupShowingPromise: function () {
            if (popup && popup.handleBeforePopupShowingPromise) {
                popup.handleBeforePopupShowingPromise.apply(popup, arguments);
            }
        },

        handleAfterLoadingModelByKey: function () {
            if (popup && popup.handleAfterLoadingModelByKey) {
                popup.handleAfterLoadingModelByKey.apply(popup, arguments);
            }
        },

        handlePopupShowing: function () {
            if (popup && popup.handlePopupShowing) {
                popup.handlePopupShowing.apply(this, arguments);
            }
        },

        handlePopupShown: function (editMode, isNewInPopup, dataModel) {
            if (popup && popup.handlePopupShown) {
                popup.handlePopupShown.apply(this, arguments);
            }
        },

        handleSaveButtonInPopup: function (isInsert) {
            if (isInsert === false) {
                if (popup && popup.handleAfterSave) {
                    popup.handleAfterSave(undefined);
                }
            }
        },

        handleAfterSaveInPopup: function (responseKey, response) {

            if (popup && popup.handleAfterSave) {
                popup.handleAfterSave(responseKey, response);
            }
        },

        getAddedToolbarItemsInPopup: function (e) {

            var isEditModeInPopup = e.isEditModeInPopup;
            var addedTooolbarItems = [
            {
                location: 'after', widget: 'button', options: {
                    text: $G('facilityInsertion'), icon: 'search', visible: isEditModeInPopup,
                    clickAction: function () { popup.facilitySearchPopup.show(); }
                }
            },
            {
                location: 'after', widget: 'button', options: {
                    text: $G('facilityDeletion'), icon: 'remove', type: 'danger', visible: isEditModeInPopup,
                    clickAction: function () {
                        if (popup && popup.handleDeleteSelectedFacilities) { popup.handleDeleteSelectedFacilities(); }
                    }
                }
            }];

            // 실행계획조회 인 경우 툴바아이템 추가 
            if (!_.isUndefined(executionPlanPopupOptions)) {
                var executionToolbarItems = executionPlanPopupOptions.getAddedToolbarItemsInPopup(e);
                var resultToolbarItems = addedTooolbarItems.concat(executionToolbarItems);
                return resultToolbarItems;
            }
            return addedTooolbarItems;
        },

        beforeInsertingDataViewModel: function (dataModel) {

            //if (popup && popup.beforeInsertingDataViewModel) {
            //    popup.beforeInsertingDataViewModel();
            //}
            //dataModel.ProgressId($Code.WorkProgress.WORK_PLAN);
            //dataModel.RequestDate(new Date());
            return true; // hcLee 2015 11 30
        },

        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', SiteId),
                   and,
                   [eq('BusinessFieldId', BWA.UserInfo.BusinessFieldId()), 'or', eq('BusinessFieldId', 1)]
                ]);
            }

            $.when(
                businessFieldDataSource.load(),
                workTypeDataSource.load(),
                progressDataSource.load()

            ).done(function (businessFieldResult, workTypeResult, progressResult) {
                businessFields(businessFieldResult[0]);
                workTypes(workTypeResult[0]);
                progresses(progressResult[0]);
                businessFieldsForSearch($SearchView.createArrayOfSelectBox('BusinessFieldId', businessFields()));
                workTypesForSearch($SearchView.createArrayOfSelectBox('WorkTypeId', workTypes()));
                progressesForSearch($SearchView.createArrayOfSelectBox('ProgressId', progresses()));
                deferredForSearch.resolve();
            });
        },

        handleViewShown: function () {

        }
    });

    viewModel.businessFields = businessFields;
    viewModel.workTypes = workTypes;
    viewModel.executionPlanViewOptions = executionPlanViewOptions;
    viewModel.executionPlanPopupOptions = executionPlanPopupOptions; // hcLee 2016 06 16
    popup = viewModel.popup = BWA.Popup.CivilComplaint.create(viewInfo, viewModel, executionPlanPopupOptions);

    return viewModel;
};