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

    var initialized = false,
        shouldReload = false,
        datagrid = null,
        currentTabIndex = ko.observable(0),
        facilityViewModel = new BWA.CmFacilityViewModel(),
        dataSource;

    var m_Facility;

   
    var facilityDataSource = BWA.db.createDataSource('CmFacility'),
        facilitiesForSearch = ko.observableArray(),

        facilityCodeForSearch = ko.observable(0),

        facilityTypeDataSource = BWA.db.createDataSource('BemsFacilityType'),
        facilityTypes = ko.observableArray(),

        formulaDataSource = BWA.db.createDataSource('BemsFormulaBase'),
        formulas = ko.observableArray(),

        deferredForSearch = new $.Deferred();

    var  visiblePopup = ko.observable(false);

    var formulaGet = new BWA.Chart.FormulaGet(BWA.UserInfo.SiteId());

    var timeBoxForSearch = BWA.SearchView.createDateTimeBox($G.TimeTypesForHourOnly, null, false);


    // 추가 2015 04 20 hcLee ->
    var CODE = $Code,
    FuelType = CODE.FuelType,
    FT = CODE.FacilityType,
    FC = CODE.FacilityCode,
    F = CODE.Formula,
    TIT = CODE.TimeIntervalType;
    // 추가 2015 04 20 hcLee  <-

    //dataMonthForBar(dataDayForBar());

    //dataDayForPie([
    //    { FuelTypeName: '전기', Value: 320 },
    //    { FuelTypeName: '가스', Value: 350 },
    //    { FuelTypeName: '수도', Value: 360 },
    //]);
    //dataMonthForPie(dataDayForPie());

    function handleViewShown() {
        window.$SearchView.isNotUse(true);
        //popupSearchViewVisible(false);

        if (initialized === false) {

            timeBoxForSearch.setDefaultDate();

            facilityTypeDataSource.filter([
                ['FacilityTypeId', '<', 20]/*,
                'and',
                ['FacilityTypeId', '<>', 1],
                'and',
                ['FacilityTypeId', '<>', 2],
                'and',
                ['FacilityTypeId', '<>', 8],*/
            ]);

            //$.when(facilityDataSource.load(), facilityTypeDataSource.load())
            $.when(facilityTypeDataSource.load())
            .done(function (facilityTypes) {
                //var facilities = facilities[0];
                //facilitiesForSearch(facilities);
                facilityTypes = facilityTypes;
                ($("#acFacilityTypeCombo").dxSelectBox("instance")).option('dataSource', facilityTypes);
                ($("#acFacilityTypeCombo").dxSelectBox("instance")).option('value', facilityTypes[0].FacilityTypeId());
                /*
                $("#acFacilityTypeCombo").dxSelectBox({
                    //placeholder: "설비 타입",
                    dataSource: facilityTypes,
                    displayExpr: "Name",
                    valueExpr: "FacilityTypeId"
                });*/
                //handleSelectedFacilityInSearchView(f);
                //handleSearchInSearchView();
                //$SearchView.visibleObservable(true);
                //$SearchView.toggleSearchView();

            });
            initialized = true;
        }
        //$SearchView.visibleObservable(true);
        //$SearchView.toggleSearchView();
        
        //$SearchView.setPopupVisibleObservable(null);
    }

    if (shouldReload) {
            //shouldReload = false;
            //dataSource.pageIndex(0);
            //dataSource.load();
    }

    function handleViewHidden() {
        //paging.hideNextButton(true);
        //paging.hidePrevButton(true);
        //$SearchView.visibleObservable(false); // hcLee 2015 03 23
        visiblePopup(false);
    }

    function handleViewShowing() {

    }

    function refreshList() {
        //dataSource.pageIndex(0);
        //dataSource.load();
    }
/*
    var searchViewOptions = {
        searchViewItems: [],
        promiseDataInSearchView: deferredForSearch.promise()
    };*/

    function handleChangedValueFT(e) {
        facilityDataSource.filter([['FacilityTypeId', '=', e.value]]);
        formulaDataSource.filter([['FacilityTypeId', '=', e.value]]);

        $.when(facilityDataSource.load(), formulaDataSource.load())
        .done(function (facilities, fs) {
            facilitiesForSearch = facilities[0];
            formulas = fs[0];
            formulas.unshift({ FormulaId: 0, Name: '미선택' });
            ($("#acFacilityCombo").dxSelectBox("instance")).option('dataSource', facilitiesForSearch);
            ($("#acFacilityCombo").dxSelectBox("instance")).option('value', facilitiesForSearch[0].FacilityCode());

            ($("#acLeftFormulaCombo").dxSelectBox("instance")).option('dataSource', formulas);
            ($("#acRightFormulaCombo").dxSelectBox("instance")).option('dataSource', formulas);

            ($("#acLeftFormulaCombo").dxSelectBox("instance")).option('value', 0);
            ($("#acRightFormulaCombo").dxSelectBox("instance")).option('value', 0);
        });
    }

    function handleChangedValueFC(e) {
        /*
        $.when(facilityDataSource.load())
        .done(function (facilities) {
            facilitiesForSearch = facilities;
            ($("#acFacilityCombo").dxSelectBox("instance")).option('dataSource', facilitiesForSearch);
        });*/
    }

    function handleChangedValueFM(e) {
        /*
        $.when(facilityDataSource.load())
        .done(function (facilities) {
            facilitiesForSearch = facilities;
            ($("#acFacilityCombo").dxSelectBox("instance")).option('dataSource', facilitiesForSearch);
        });*/
    }

    function ChartProcess(DataArray, valueAx, seriesF) {
        $("#acChart").dxChart({
            dataSource: DataArray,
            palette: "Pastel",
            legend: {
                visible: true,
                verticalAlignment: 'top',
                horizontalAlignment: 'center'
            },

            commonAxisSettings: {
                title: {
                    valueMarginsEnabled: true,
                    margin: 20,
                    font: {
                        color: "black",
                        size: 18,
                        weight: 600,
                        family: "Nanum Gothic",
                    },
                },
                axisDivisionFactor: 50,
                grid: {
                    visible: true,
                }
            },
            commonSeriesSettings: {
                argumentField: "DateTime",
                selectionStyle: {
                    hatching: {
                        direction: "left"
                    }
                }
            },
            valueAxis: valueAx,

            series: seriesF,

            crosshair: {
                enabled: true,
                width: 1,
                horizontalLine: {
                    color: '#452d11',
                    dashStyle: 'dash',
                    visible: true
                },
                verticalLine: {
                    color: '#452d11',
                    dashStyle: 'dash',
                    visible: true
                },
                label: {
                    visible: true,
                    backgroundColor: "#452d11",
                    font: {
                        color: "white",
                        size: 12,
                        weight: 600,
                    }
                }
            },
            tooltip: {
                enabled: true,
                color: "#3e1717",
                format: 'fixedPoint',
                precision: 2,
                font: {
                    color: "white",
                    size: 12,
                    weight: 600,
                },
                argumentFormat: 'shortDate',
                customizeText: function () {
                    return {
                        text: [this.argumentText, ': ', this.valueText].join('')
                    };
                }
            },
        });
    }

    function LeftProcess(promises, LeftFormulaName, Y_Left_ChartType) {
        /*
                // 외기 온도와 습도를 위해 추가 hcLee 2015 04 20  ->
                var commonParameters = {
                    TimeIntervalType: $Code.TimeIntervalType.QUARTERMIN,
                    StartDate: date.startDate,
                    EndDate: date.endDate
                };
                var temperatureParameters = {
                    FacilityTypeId: FT.OUTDOOR,
                    FacilityCode: FC.OUTDOOR,
                    FormulaId: F[FT.OUTDOOR].TEMPERATURE,
                };
                promises.push(formulaGet.apiGet(_.extend(temperatureParameters, commonParameters)));
        */  // 보일러는 필요 없다
        $.when.apply(this, promises)
        .done(function (data) {
            var DataArray = [];
            var maxValue = 0;
            _.each(data, function (x) {
                if (maxValue < x.Value) maxValue = x.Value;
                DataArray.push({
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(2, moment(x.DateTime).toDate()),
                    value1: x.Value
                });
            });

            var valueAx = {};
            $.extend(valueAx, {
                //pane: 'topPane',
                name: 'left',
                position: 'left',
                label: {
                    visible: true,
                    format: 'fixedPoint',
                    precision: 0,
                },
                title: { text: LeftFormulaName },
                tickInterval: Math.round(maxValue / 5) + 1,
            });

            var seriesF = {};
            $.extend(seriesF, {
                type: Y_Left_ChartType,
                axis: 'left',
                valueField: 'value1',
                name: LeftFormulaName,
            });

            ChartProcess(DataArray, valueAx, seriesF);
            visiblePopup(false);

        })
        .fail(function (error) {
            //alert(error);
            visiblePopup(false);
        });
        visiblePopup(false);
    }

    function RightProcess(promises, RightFormulaName, Y_Right_ChartType) {
        $.when.apply(this, promises)
        .done(function (data) {
            var DataArray = [];
            var maxValue = 0;
            _.each(data, function (x) {
                if (maxValue < x.Value) maxValue = x.Value;
                DataArray.push({
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(2, moment(x.DateTime).toDate()),
                    value1: x.Value
                });
            });

            var valueAx = {};
            $.extend(valueAx, {
                //pane: 'topPane',
                name: 'right',
                position: 'right',
                label: {
                    visible: true,
                    format: 'fixedPoint',
                    precision: 0,
                },
                title: { text: RightFormulaName },
                tickInterval: Math.round(maxValue / 5) + 1,
            });

            var seriesF = {};
            $.extend(seriesF, {
                type: Y_Right_ChartType,
                axis: 'right',
                valueField: 'value1',
                name: RightFormulaName,
            });

            ChartProcess(DataArray, valueAx, seriesF);
            visiblePopup(false);
        })
        .fail(function (error) {
            //alert(error);
            visiblePopup(false);
        });
        visiblePopup(false);
    }

    function BothProcess(promises, LeftFormulaName, Y_Left_ChartType, RightFormulaName, Y_Right_ChartType) {
        $.when.apply(this, promises)
        .done(function (dataL, dataR) {
            var DataArray = [];
            var maxValueL = 0;
            var maxValueR = 0;
            _.each(dataL[0], function (x) {
                if (maxValueL < x.Value) maxValueL = x.Value;
                DataArray.push({
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(2, moment(x.DateTime).toDate()),
                    valueL: x.Value
                });
            });
            _.each(dataR[0], function (x) {
                if (maxValueR < x.Value) maxValueR = x.Value;
                DataArray.push({
                    DateTime: BWA.Chart.getCustermTimeArgumentAxisString(2, moment(x.DateTime).toDate()),
                    valueR: x.Value
                });
            });

            var valueAx = [
             {
                 name: 'left',
                 position: 'left',
                 label: { visible: true, },
                 title: { text: LeftFormulaName },
                 tickInterval: Math.round(maxValueL / 5) + 1,
             },
             {
                 name: 'right',
                 position: 'right',
                 label: { visible: true, },
                 title: { text: RightFormulaName },
                 tickInterval: Math.round(maxValueR / 5) + 1,
             }];

            var seriesF = [
            {
                type: Y_Left_ChartType,
                axis: 'left',
                valueField: 'valueL',
                name: LeftFormulaName,
            },
            {
                type: Y_Right_ChartType,
                axis: 'right',
                valueField: 'valueR',
                name: RightFormulaName,
            }];

            ChartProcess(DataArray, valueAx, seriesF);
            visiblePopup(false);
        })
        .fail(function (error) {
            //alert(error);
            visiblePopup(false);
        });
        visiblePopup(false);
    }

    function handleSearchInSearchView(filter, searchViewItems) {

        var facilityTypeId = $("#acFacilityTypeCombo").dxSelectBox('instance').option('value');
        var facilityCode = $("#acFacilityCombo").dxSelectBox('instance').option('value');
        
        var LeftFormulaId = $("#acLeftFormulaCombo").dxSelectBox('instance').option('value');
        var LeftFormulaName = $("#acLeftFormulaCombo").dxSelectBox('instance').option('text');
        var Y_Left_ChartType = $("#acLeftChartTypeCombo").dxSelectBox('instance').option('text');

        var RightFormulaId = $("#acRightFormulaCombo").dxSelectBox('instance').option('value');
        var RightFormulaName = $("#acRightFormulaCombo").dxSelectBox('instance').option('text');
        var Y_Right_ChartType = $("#acRightChartTypeCombo").dxSelectBox('instance').option('text');

        if (facilityTypeId == null || facilityCode == null) {
            utils.toast.show('설비 타입과 설비 선택은 필수 입니다!', 'error');
            return;
        }
        if (LeftFormulaId == 0 && RightFormulaId == 0) {
            utils.toast.show('분석식을 하나 이상 선택해야 합니다.', 'error');
            return;
        }

        //var f = m_Facility.toJS();
        //facilityViewModel.fromJS(f);
        var timeIntervalType = timeBoxForSearch.type();
        var date = timeBoxForSearch.getDate();
        visiblePopup(true);
        $("#large-indicator").dxLoadIndicator({
            height: 60,
            width: 60
        });

        var promises = [];
        if (LeftFormulaId > 0 && RightFormulaId > 0) {
            var p = formulaGet.apiGet({
                FacilityTypeId: facilityTypeId,
                FacilityCode: facilityCode,
                FormulaId: LeftFormulaId,
                TimeIntervalType: timeIntervalType,
                StartDate: date.startDate,
                EndDate: date.endDate
            });
            promises.push(p);
            p = formulaGet.apiGet({
                FacilityTypeId: facilityTypeId,
                FacilityCode: facilityCode,
                FormulaId: RightFormulaId,
                TimeIntervalType: timeIntervalType,
                StartDate: date.startDate,
                EndDate: date.endDate
            });
            promises.push(p);
            BothProcess(promises, LeftFormulaName, Y_Left_ChartType, RightFormulaName, Y_Right_ChartType);
        }
        else if (LeftFormulaId > 0) {
            var p = formulaGet.apiGet({
                FacilityTypeId: facilityTypeId,
                FacilityCode: facilityCode,
                FormulaId: LeftFormulaId,
                TimeIntervalType: timeIntervalType,
                StartDate: date.startDate,
                EndDate: date.endDate
            });
            promises.push(p);
            LeftProcess(promises, LeftFormulaName, Y_Left_ChartType);
        }
        else if (RightFormulaId > 0) {
            var p = formulaGet.apiGet({
                FacilityTypeId: facilityTypeId,
                FacilityCode: facilityCode,
                FormulaId: RightFormulaId,
                TimeIntervalType: timeIntervalType,
                StartDate: date.startDate,
                EndDate: date.endDate
            });
            promises.push(p);
            RightProcess(promises,RightFormulaName, Y_Right_ChartType);
        }
    }

    var viewModel = $.extend(BWA.CommonView.create(
            params, viewInfo, null, ko.observable(null),
            handleViewShown, null, handleSearchInSearchView, undefined), {

//        facility: facilityViewModel,
                refreshList: refreshList,
                viewHidden: handleViewHidden, // hcLee 2015 06 03
        viewShowing: handleViewShowing,
        contentReadyAction: function(e) {
            datagrid = e.component;
        }
    });

    viewModel.popupOptions = {
        width: 300,
        height: 100,
        contentTemplate: "info",
        showTitle: false,
        title: "메세지",
        visible: visiblePopup,
        dragEnabled: false,
        shading:false,
        closeOnOutsideClick: false
    };

    viewModel.timeBoxForSearch = timeBoxForSearch;
    viewModel.currentTabIndex = currentTabIndex;
    viewModel.facilityTypes = facilityTypes;
    viewModel.handleChangedValueFT = handleChangedValueFT;
    viewModel.handleChangedValueFC = handleChangedValueFC;
    viewModel.handleChangedValueFM = handleChangedValueFM;
    viewModel.facilitiesForSearch = facilitiesForSearch;
    viewModel.formulas = formulas;

    return viewModel;
};