BemsWebApplication.ChargePrice2 = function (params, viewInfo) {
    var now = new Date();
    var selectEnergy = "전력";
    var priceType = new Array(2);
    var priceCodes;
    var selectedItem;
    var init = false;
    var handleViewShowninit;
    var endpointSelector = "";
    if (BemsWebApplication.config.mode == "production") {
        endpointSelector = new DevExpress.EndpointSelector(BemsWebApplication.config.endpoints).config.db.production;
    } else {
        endpointSelector = new DevExpress.EndpointSelector(BemsWebApplication.config.endpoints).config.db.local;
    }

    //권한설정
    var hasnotModificationPermission = ko.observable(true);

    //탭 표시 요금제 Array 데이터 초기화
    var tabsData = [
    {
        id: "0",
        text: "test1"
    },
    {
        id: "1",
        text: "test2"
    },
    {
        id: "2",
        text: "test3"
    }
    ];

    function setPriceCodeData(SiteID, FuelTypeId) {
        var dataSource = new DevExpress.data.DataSource({
            store: new DevExpress.data.ODataStore({
                url: endpointSelector + "/BemsSitePrice"
            }),
            expand: ['BemsPriceCode', 'BemsPriceType'],
            requireTotalCount: true,
            pageSize: 1000
        });
        dataSource.filter([
            ["SiteID", "=", SiteID],
            "and",
            ["FuelTypeId", "=", FuelTypeId],
            "and",
            ["UseYN", "=", "Y"],
            "and",
            ["PriceTypeId", "=", parseInt($("#tabOptions").dxTabs("instance").option('selectedItem').id)]
        ]);
        dataSource.sort({ getter: "PriceCode", asc: true });
        dataSource.load()
        .done(function (result) {
            if (result.length == 0) {
                return;
            }
            priceType[0] = result[0].PriceTypeId;
            priceType[1] = result[0].BemsPriceType.PriceTypeIdDesc;
            //$('#priceTypeId').text(priceType[1]);
            var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
            var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
            $("#startDate").dxDateBox("instance").option('value', new Date(tmpDate.getFullYear(), tmpDate.getMonth() - 1, 1, 0, 0, 0, 0));
            $("#endDate").dxDateBox("instance").option('value', new Date(tmpDate.getFullYear(), tmpDate.getMonth() - 1, endDay, 0, 0, 0, 0));
            var $detail = $('#detail'); // finds the <detail> element
            $('#detail').empty();
            priceCodes = new Array();
            for (var i = 0; i < result.length; i++) {
                priceCodes[i] = result[i].PriceCode;
                //<div class="dx-field-label cw-multi-field-label-ex">기본요금</div>
                //<div id="labelBaseCharge" class="dx-field-value" data-bind="text: '6,240,000'"></div>
                //<div id="txtBaseCharge" style="margin-left: 10px; position: absolute; left: 14%;" data-bind="dxTextBox: { value: '6,240,000' , placeholder: '기본요금' , visible : false}"></div>
                $('<div class="fl setText" style="line-height:220%;cursor:default;background:#d5ecfd url(../images/custom/ibems_light/arrow01.png) 5px center no-repeat;padding-left:15px;width:15%;height:32px;"></div>')                 // creates a new HTML element
                    .appendTo($detail)     // appends a new HTML element to the <body> element
                $('<div class="fl setInput" style="margin-left: 10px;width:15%;" data-bind="dxTextBox: {}"></div>')
                    .appendTo($detail)
                    .dxTextBox();
                if (i % 3 == 2) {
                    $('<br>').appendTo($detail)
                    $('<br>').appendTo($detail)
                }
            }
            var setTexts = document.querySelectorAll('.setText');
            var setInputs = document.querySelectorAll('.setInput');
            for (var i = 0; i < result.length; i++) {
                setTexts[i].id = "text" + result[i].PriceCode;
                setTexts[i].innerHTML = result[i].BemsPriceCode.PriceCodeDesc;
                setInputs[i].id = result[i].PriceCode;
                //$('#switch' + i).dxSwitch("instance").option('onText', 'On');
                //$('#switch' + i).dxSwitch("instance").option('offText', 'Off');
            }
        })
        .fail(function (error) {
            utils.toast.show(error);
        });
    }

    function getHistoryData(SiteId, FuelTypeId, PayDate) {
        var dataSource = new DevExpress.data.DataSource({
            store: new DevExpress.data.ODataStore({
                url: endpointSelector + "/BemsSitePriceHistory"
            }),
            expand: ['BemsPriceCode', 'BemsPriceType'],
            requireTotalCount: true,
            pageSize: 100
        });
        dataSource.filter([
                ["SiteId", "=", SiteId],
                "and",
                ["FuelTypeId", "=", FuelTypeId],
                "and",
                ["PayDate", "=", PayDate],
                "and",
                ["PriceTypeId", "=", parseInt($("#tabOptions").dxTabs("instance").option('selectedItem').id)]
        ]);
        dataSource.load()
        .done(function (result) {
            priceType[0] = result[0].PriceTypeId;
            priceType[1] = result[0].BemsPriceType.PriceTypeIdDesc;
            //$('#priceTypeId').text(priceType[1]);
            //$('#priceTypeId').text(priceType[1]);
            var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
            var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
            $("#startDate").dxDateBox("instance").option('value', result[0].StartDate);
            $("#endDate").dxDateBox("instance").option('value', result[0].EndDate);
            $("#startDate").dxDateBox("instance").option('readOnly', true);
            $("#endDate").dxDateBox("instance").option('readOnly', true);
            var $detail = $('#detail'); // finds the <detail> element
            $('#detail').empty();
            priceCodes = new Array();
            for (var i = 0; i < result.length; i++) {
                priceCodes[i] = result[i].PriceCode;
                $('<div class="fl setText" style="line-height:220%;cursor:default;background:#d5ecfd url(../images/custom/ibems_light/arrow01.png) 5px center no-repeat;padding-left:15px;width:15%;height:32px;"></div>')                 // creates a new HTML element
                    .appendTo($detail)     // appends a new HTML element to the <body> element
                $('<div class="fl setInput" style="margin-left: 10px;width:15%;" data-bind="dxTextBox: {}"></div>')
                    .appendTo($detail)
                    .dxTextBox();
                if (i % 3 == 2) {
                    $('<br>').appendTo($detail)
                    $('<br>').appendTo($detail)
                }
            }
            var setTexts = document.querySelectorAll('.setText');
            var setInputs = document.querySelectorAll('.setInput');
            for (var i = 0; i < result.length; i++) {
                setTexts[i].id = "text" + result[i].PriceCode;
                setTexts[i].innerHTML = result[i].BemsPriceCode.PriceCodeDesc;
                setInputs[i].id = result[i].PriceCode;
                $('#' + result[i].PriceCode).dxTextBox("instance").option('value', result[i].PriceValue);
                $('#' + result[i].PriceCode).dxTextBox("instance").option('readOnly', true);
                //$('#switch' + i).dxSwitch("instance").option('offText', 'Off');
            }
        })
        .fail(function (error) {
            utils.toast.show(error);
        });
    }

    function checkHistoryData(SiteId, FuelTypeId, PayDate) {
        var dataSource = new DevExpress.data.DataSource({
            store: new DevExpress.data.ODataStore({
                url: endpointSelector + "/BemsSitePriceHistory"
            }),
            requireTotalCount: true,
            pageSize: 100
        });
        dataSource.filter([
                ["SiteId", "=", SiteId],
                "and",
                ["FuelTypeId", "=", FuelTypeId],
                "and",
                ["PayDate", "=", PayDate],
                "and",
                ["PriceTypeId", "=", parseInt($("#tabOptions").dxTabs("instance").option('selectedItem').id)]
        ]);
        dataSource.load()
        .done(function (result) {
            if (result.length == 0) {
                $("#modifyBtn").dxButton("instance").option("text", "입력");
                if (!init) {
                    if (handleViewShowninit) {
                        setTabData(BWA.UserInfo.SiteId(), FuelTypeId, true);
                        handleViewShowninit = false;
                    }
                    else
                        setTabData(BWA.UserInfo.SiteId(), FuelTypeId, false);
                } else {
                    setPriceCodeData(BWA.UserInfo.SiteId(), FuelTypeId);
                }
            } else {
                $("#modifyBtn").dxButton("instance").option("text", "수정");
                if (!init) {
                    setTabData(BWA.UserInfo.SiteId(), FuelTypeId, true);
                } else {
                    getHistoryData(BWA.UserInfo.SiteId(), FuelTypeId, PayDate);
                }
            }
        })
        .fail(function (error) {
            utils.toast.show(error);
        });
    }

    function insertSitePriceHistory(SiteId, FuelTypeId, PayDate) {
        var store = new DevExpress.data.ODataStore({
            url: endpointSelector + "/BemsSitePriceHistory",
            key: ["SiteId", "FuelTypeId", "PriceTypeId", "PriceCode", "PayDate"],
            keyType: { SiteId: "Int32", FuelTypeId: "Int32", PriceTypeId: "Int32", PriceCode: "String", PayDate: "String" }
        });
        var failCnt = 0;
        var startDate = $("#startDate").dxDateBox("instance").option('value');
        var endDate = $("#endDate").dxDateBox("instance").option('value');
        for (var i = 0; i < priceCodes.length; i++) {
            var priceValue = $("#" + priceCodes[i]).dxTextBox("instance").option('value');
            store.insert({
                SiteId: SiteId, FuelTypeId: FuelTypeId, PriceTypeId: priceType[0], PriceCode: priceCodes[i], PriceValue: priceValue, PayDate: PayDate, StartDate: startDate, EndDate: endDate, PayCharge: "0"
            })
            .done(function (key, result) {
                //utils.toast.show(key + "/" + result);
            })
            .fail(function (error) {
                failCnt++;
            });
        }
        if (failCnt > 0) {
            utils.toast.show("저장이 실패했습니다.");
        } else {
            utils.toast.show("저장이 완료 되었습니다.");
        }
    }

    function updateSitePriceHistory(SiteId, FuelTypeId, PayDate) {
        var failCnt = 0;
        var store = new DevExpress.data.ODataStore({
            url: endpointSelector + "/BemsSitePriceHistory",
            key: ["SiteId", "FuelTypeId", "PriceTypeId", "PriceCode", "PayDate"],
            keyType: { SiteId: "Int32", FuelTypeId: "Int32", PriceTypeId: "Int32", PriceCode: "String", PayDate: "String" }
        });
        var startDate = $("#startDate").dxDateBox("instance").option('value');
        var endDate = $("#endDate").dxDateBox("instance").option('value');
        for (var i = 0; i < priceCodes.length; i++) {
            var priceValue = $("#" + priceCodes[i]).dxTextBox("instance").option('value');
            store.update({ SiteId: SiteId, FuelTypeId: FuelTypeId, PriceTypeId: priceType[0], PriceCode: priceCodes[i], PayDate: PayDate }, { PriceValue: priceValue, StartDate: startDate, EndDate: endDate })
            .done(function (key, result) {
                //utils.toast.show(key + "/" + result);
            })
            .fail(function (error) {
                failCnt++;
            });
        }
        if (failCnt > 0) {
            utils.toast.show("업데이트가 실패했습니다.");
        } else {
            utils.toast.show("저장 되었습니다.");
        }
    }

    function disableReadOnly() {
        for (var i = 0; i < priceCodes.length; i++) {
            $("#" + priceCodes[i]).dxTextBox("instance").option('readOnly', false);
        }
        $("#startDate").dxDateBox("instance").option('readOnly', false);
        $("#endDate").dxDateBox("instance").option('readOnly', false);
    }

    function enableReadOnly() {
        for (var i = 0; i < priceCodes.length; i++) {
            $("#" + priceCodes[i]).dxTextBox("instance").option('readOnly', true);
        }
        $("#startDate").dxDateBox("instance").option('readOnly', true);
        $("#endDate").dxDateBox("instance").option('readOnly', true);
    }

    function setTabData(SiteID, FuelTypeId, HistoryDataYN) {
        var dataSource;
        if (!HistoryDataYN) {
            dataSource = new DevExpress.data.DataSource({
                store: new DevExpress.data.ODataStore({
                    url: endpointSelector + "/BemsSitePrice"
                }),
                expand: ['BemsPriceType'],
                requireTotalCount: true,
                pageSize: 1000
            });
            dataSource.filter([
                    ["SiteID", "=", SiteID],
                    "and",
                    ["FuelTypeId", "=", FuelTypeId]
            ]);
        } else {
            dataSource = new DevExpress.data.DataSource({
                store: new DevExpress.data.ODataStore({
                    url: endpointSelector + "/BemsSitePriceHistory"
                }),
                expand: ['BemsPriceType'],
                requireTotalCount: true,
                pageSize: 1000
            });
            var searchDate = $("#startDatePicker").dxDateBox("instance").option('value');
            var tmpMonth = (searchDate.getMonth() + 1).toString();
            if (tmpMonth.length == 1) {
                tmpMonth = "0" + tmpMonth;
            }
            dataSource.filter([
                    ["SiteId", "=", SiteID],
                    "and",
                    ["FuelTypeId", "=", FuelTypeId],
                    "and",
                    ["PayDate", "=", searchDate.getFullYear().toString() + tmpMonth]
            ]);
        }
        dataSource.sort({ getter: "FuelTypeId", asc: true });
        dataSource.load()
        .done(function (result) {
            if (result.length == 0 && HistoryDataYN == true) {
                setTabData(SiteID, FuelTypeId, false);
                return;
            }
            var tmp = [];
            tmp.push({ id: result[0].BemsPriceType.PriceTypeId, text: result[0].BemsPriceType.PriceTypeIdDesc });
            for (var i = 0; i < result.length; i++) {
                var resultCnt;
                for (var j = 0; j < tmp.length; j++) {
                    if (tmp[j].text.indexOf(result[i].BemsPriceType.PriceTypeIdDesc) != -1) {
                        resultCnt++;
                    }
                }
                if (resultCnt == 0)
                    tmp.push({ id: result[i].BemsPriceType.PriceTypeId, text: result[i].BemsPriceType.PriceTypeIdDesc });
                resultCnt = 0;
            }
            tabsData = tmp;
            $("#tabOptions").dxTabs("instance").option('dataSource', tabsData);
            if (!init) {
                $("#tabOptions").dxTabs("instance").option('selectedIndex', 0);
                init = true;
            } else {

            }
            if (!HistoryDataYN) {
                setPriceCodeData(BWA.UserInfo.SiteId(), FuelTypeId);
            } else {
                var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
                var month = tmpDate.getMonth() + 1;
                if (month < 10) {
                    month = "0" + month.toString();
                }
                getHistoryData(BWA.UserInfo.SiteId(), FuelTypeId, tmpDate.getFullYear().toString() + month);
            }
        });
    }

    function handleViewShown() {
        //권한설정
        hasnotModificationPermission(!BWA.UserInfo.hasPermissionOfModification(viewInfo.viewName));

        init = false;
        var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
        var month = tmpDate.getMonth() + 1;
        if (month < 10) {
            month = "0" + month.toString();
        }
        var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
        $("#powerBtn").css("background-image", "linear-gradient(180deg,#9babc3 0%,#41618c 100%)");
        $("#gasBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
        $("#waterBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
        selectEnergy = "전력";
        handleViewShowninit = true;
        //checkHistoryData(BWA.UserInfo.SiteId(), 1, tmpDate.getFullYear().toString() + month);//먼가 오류? 하단의 내용으로 변경190820
        setTabData(BWA.UserInfo.SiteId(), 1, false);
        setTimeout(function () {
            checkHistoryData(BWA.UserInfo.SiteId(), 1, tmpDate.getFullYear().toString() + month);
        }, 1000);
    }

    var searchViewOptions = {
        //templete function
    };

    function handleSearchInSearchView() {
        //templete function
    }

    var viewModel = $.extend(BWA.CommonView.create(params, viewInfo, searchViewOptions, ko.observable(null), handleViewShown, null, handleSearchInSearchView),
        {
            startDatePicker: {
                pickerType: "calendar",
                value: now,
                formatString: "yyyy년 MM월",
                maxZoomLevel: "year",
                width: "9%",
                onValueChanged: function () {
                    var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
                    var month = tmpDate.getMonth() + 1;
                    if (month < 10) {
                        month = "0" + month.toString();
                    }
                    var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
                    var FuelTypeId = 0;
                    if (selectEnergy == "전력") {
                        FuelTypeId = 1;
                    } else if (selectEnergy == "가스") {
                        FuelTypeId = 2;
                    } else if (selectEnergy == "수도") {
                        FuelTypeId = 3;
                    } else {
                        utils.toast.show("선택된 에너지원이 없습니다.");
                    }
                    init = false;
                    //checkHistoryData(BWA.UserInfo.SiteId(), FuelTypeId, tmpDate.getFullYear().toString() + month); //먼가 오류? 하단의 내용으로 변경190820
                    setTabData(BWA.UserInfo.SiteId(), FuelTypeId, false);
                    setTimeout(function () {
                        checkHistoryData(BWA.UserInfo.SiteId(), FuelTypeId, tmpDate.getFullYear().toString() + month);
                    }, 1000);
                }
            },
            startDate: {
                pickerType: "calendar",
                value: now,
                formatString: "yyyy년 MM월 dd일",
                maxZoomLevel: "month",
                width: "12%"
            },
            endDate: {
                pickerType: "calendar",
                value: now,
                formatString: "yyyy년 MM월 dd일",
                maxZoomLevel: "month",
                width: "12%"
            },
            powerButtonClicked: function () {
                init = false;
                $("#tabOptions").dxTabs("instance").option('selectedIndex', 0);
                $("#powerBtn").css("background-image", "linear-gradient(180deg,#9babc3 0%,#41618c 100%)");
                $("#gasBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
                $("#waterBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
                selectEnergy = "전력";
                var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
                var month = tmpDate.getMonth() + 1;
                if (month < 10) {
                    month = "0" + month.toString();
                }
                var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
                setTabData(BWA.UserInfo.SiteId(), 1, false);
                setTimeout(function () {
                    checkHistoryData(BWA.UserInfo.SiteId(), 1, tmpDate.getFullYear().toString() + month);
                }, 1000);
            },
            gasButtonClicked: function () {
                init = false;
                $("#tabOptions").dxTabs("instance").option('selectedIndex', 0);
                $("#gasBtn").css("background-image", "linear-gradient(180deg,#9babc3 0%,#41618c 100%)");
                $("#powerBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
                $("#waterBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
                selectEnergy = "가스";
                var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
                var month = tmpDate.getMonth() + 1;
                if (month < 10) {
                    month = "0" + month.toString();
                }
                var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
                setTabData(BWA.UserInfo.SiteId(), 2, false);
                setTimeout(function () {
                    checkHistoryData(BWA.UserInfo.SiteId(), 2, tmpDate.getFullYear().toString() + month);
                }, 1000);
            },
            waterButtonClicked: function () {
                init = false;
                $("#tabOptions").dxTabs("instance").option('selectedIndex', 0);
                $("#waterBtn").css("background-image", "linear-gradient(180deg,#9babc3 0%,#41618c 100%)");
                $("#gasBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
                $("#powerBtn").css("background-image", "linear-gradient(rgb(56,88,130) 0%, rgb(44,68,101)100%)");
                selectEnergy = "수도";
                var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
                var month = tmpDate.getMonth() + 1;
                if (month < 10) {
                    month = "0" + month.toString();
                }
                var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
                setTabData(BWA.UserInfo.SiteId(), 3, false);
                setTimeout(function () {
                    checkHistoryData(BWA.UserInfo.SiteId(), 3, tmpDate.getFullYear().toString() + month);
                }, 1000);
            },
            modifyButtonClicked: function () {
                var FuelTypeId = 0;
                if (selectEnergy == "전력") {
                    FuelTypeId = 1;
                } else if (selectEnergy == "가스") {
                    FuelTypeId = 2;
                } else if (selectEnergy == "수도") {
                    FuelTypeId = 3;
                } else {
                    utils.toast.show("선택된 에너지원이 없습니다.");
                }
                var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
                var month = tmpDate.getMonth() + 1;
                if (month < 10) {
                    month = "0" + month.toString();
                }
                var payDate = tmpDate.getFullYear().toString() + month;
                if ($("#modifyBtn").dxButton("instance").option("text") == "입력") {
                    $("#modifyBtn").dxButton("instance").option("text", "수정");
                    insertSitePriceHistory(BWA.UserInfo.SiteId(), FuelTypeId, payDate);
                    enableReadOnly();
                } else if ($("#modifyBtn").dxButton("instance").option("text") == "수정") {
                    $("#modifyBtn").dxButton("instance").option("text", "확인");
                    disableReadOnly();
                } else if ($("#modifyBtn").dxButton("instance").option("text") == "확인") {
                    $("#modifyBtn").dxButton("instance").option("text", "수정");
                    updateSitePriceHistory(BWA.UserInfo.SiteId(), FuelTypeId, payDate);
                } else {
                    utils.toast.show("선택된 버튼이 없습니다.");
                }
            },
            tabOptions: {
                //theme: 'generic.light',
                dataSource: tabsData,
                height: 20,
                selectedIndex: 0,
                onSelectionChanged: function (e) {
                    //$("#priceSelect").dxSelectBox("instance").option('value', e.addedItems[0].id);
                    selectedItem = e.addedItems[0];
                    if (init) {
                        var FuelTypeId;
                        if (selectEnergy == "전력") {
                            FuelTypeId = 1;
                        } else if (selectEnergy == "가스") {
                            FuelTypeId = 2;
                        } else if (selectEnergy == "수도") {
                            FuelTypeId = 3;
                        } else {
                            utils.toast.show("에너지원이 선택되지 않았습니다.");
                        }
                        var tmpDate = $("#startDatePicker").dxDateBox("instance").option('value');
                        var month = tmpDate.getMonth() + 1;
                        if (month < 10) {
                            month = "0" + month.toString();
                        }
                        var endDay = (new Date(tmpDate.getFullYear(), tmpDate.getMonth(), 0)).getDate();
                        checkHistoryData(BWA.UserInfo.SiteId(), FuelTypeId, tmpDate.getFullYear().toString() + month);
                    }
                }
            },
            hasnotModificationPermission: hasnotModificationPermission //권한설정
        });

    return viewModel;
};