<%@ Page Title="" Language="C#" MasterPageFile="~/MachineDeviceManagement/DeviceManagementBase.master" AutoEventWireup="true" CodeFile="AddMachineGroup.aspx.cs" Inherits="AddMachineGroup" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="<%=GetFileUrlWithVersion("../css/tabcontrol.css")%>" rel="stylesheet" />
    <link href="<%=GetFileUrlWithVersion("../css/jquery.datetimepicker.css")%>" rel="stylesheet" />
    <style type="text/css">
        ::-ms-clear, ::-ms-reveal {
            display: none;
        }

        .edit-content table {
            border-collapse: collapse;
            width: 100%;
        }

            .edit-content table td.label {
                width: 200px;
                text-align: right;
                padding-right: 10px;
                line-height: 24px;
                height: 24px;
                vertical-align: top;
            }

            .edit-content table td input,
            .edit-content table td textarea {
                border: 1px solid #a9a9a9;
                width: 200px;
                height: 18px;
                padding: 1px;
            }

                .edit-content table td input[type="checkbox"] {
                    border: none;
                    width: 13px;
                }

            .edit-content table td textarea {
                height: 100px;
                resize: none;
                /*max-width: 200px;*/
            }

            .edit-content table td select {
                height: 22px;
                width: 204px;
            }

        .a {
            text-decoration: none;
            color: #2140fb;
        }

        .subtitle {
            margin: 30px 40px 5px 0px;
            font-size: 16px;
            color: gray;
        }

            .subtitle span {
                margin-left: 10px;
            }

            .subtitle hr {
                background-color: #d8d8d8;
                border: none;
                height: 1px;
            }


        .categoryname {
            cursor: default;
            font-size: 20px;
            font-weight: bold;
            padding-top: 5px;
        }

        .plus:before {
            font-size: 10px;
            font-weight: normal;
            font-family: 'CalciteWebCoreIcons', 'Fontawesome';
            content: '\e620';
            margin-right: 5px;
        }

        .minus:before {
            font-size: 10px;
            font-weight: normal;
            font-family: 'CalciteWebCoreIcons', 'Fontawesome';
            content: '\e621';
            margin-right: 5px;
        }

        .dialogspanbtn {
            font-size: 14px;
            font-weight: normal;
            font-family: 'CalciteWebCoreIcons', 'Fontawesome';
            cursor: pointer;
            background: rgb(249, 189, 117);
            padding: 2px;
        }

        .dialogedit:before {
            content: '\e61b';
        }

        .dialogok:before {
            content: '\e605';
        }

        .dialogcancel:before {
            content: '\e600';
        }

        .dialogbtn {
            height: 24px;
            cursor: pointer;
            background: rgb(249, 189, 117);
            padding: 2px;
        }

        .machinetd {
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .popus-close {
            float: right;
            margin-right: 6px;
            cursor: pointer;
        }

            .popus-close:before {
                content: '\e600';
            }

        textarea {
            resize: none;
        }

        .divtab {
            overflow: auto;
        }

        .label {
            width: 184px;
        }

        .assetcontent table {
            border-collapse: collapse;
            width: 100%;
        }

            .assetcontent table td.label {
                width: 184px;
                text-align: right;
                padding-right: 10px;
                line-height: 24px;
                height: 24px;
                vertical-align: top;
            }

            .assetcontent table td input,
            .assetcontent table td textarea {
                border: 1px solid #a9a9a9;
                width: 200px;
                height: 18px;
                padding: 1px;
            }

                .assetcontent table td input[type="checkbox"] {
                    border: none;
                    width: 13px;
                }

            .assetcontent table td textarea {
                height: 100px;
            }

        .adjust-content table td.label {
            width: 130px;
            text-align: right;
            padding-right: 10px;
            line-height: 24px;
            height: 24px;
            vertical-align: top;
        }

        .adjust-content table td input {
            width: 200px;
        }

        .adjust-content table td select {
            width: 204px;
        }

        #divcontent {
            margin: 8px;
        }

        .dialogflatbtn {
            background-color: rgb(235, 235, 235);
            border: none;
            padding-top: 5px;
            padding-bottom: 5px;
            cursor: pointer;
            width: 80px;
        }

            .dialogflatbtn:hover {
                background: rgb(225, 225, 225);
            }
    </style>
    <script src="<%=GetFileUrlWithVersion("../Maintenance/js/inputdatactr.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/jquery.datetimepicker.full.js")%>"></script>
    <script src="<%=GetFileUrlWithVersion("../js/editableselect.js")%>"></script>
    <script src="<%=GetFileUrlWithVersion("../js/controls.js")%>" type="text/javascript"></script>
    <script src="<%=GetFileUrlWithVersion("../js/assetselector.js")%>" type="text/javascript"></script>
    <script type="text/javascript">
        var IsDealer = <%=IsDealer ?"true":"false"%>;
        var IsAdmin =<%=IsAdmin ?"true":"false"%>;
        var IsSupperAdmin =<%=IsSupperAdmin ?"true":"false"%>;
        var isAllowed = false;

        var machineGroupID = "<%=MachineID %>";
        var allMachineGroups;
        var indexInEdit;

        var onsitejobsiteid;
        var contactids;
        var MachineAttributes = [];

        var machines = [];
        var makes = [];
        var models = [];
        var machinetypes = [];

        var editableSelectMake;
        var editableSelectModel;

        var noneditwidth = 200;
        var editablewidth = 180;

        //动态加载机器列表
        var displayCountPerPage = 30;//每页显示的机器条数
        var currentShownIndex = -1;//当前显示的机器索引
        var engineHoursBeforeChange = undefined;

        var _selectedRental = null;
        var needRefreshDataOnCancel = false;//由于在Next和Previous时直接保存机器信息,在点Cancel时也需要刷新数据

        var loadingCount = 0;
        var customertimezone;
        var customerdatetime;

        function devicerequest(method, param, callback, error) {
            _network.request("MachineDeviceManagement/ManageMachines.aspx", -1, method, param, callback, error || function (e) {
                console.log(e);
                showmaskbg(false, true);
                showAlert(GetTextByKey('P_AG_PAGEERROR', 'An unknown error occurred.  Please refresh page.'), GetTextByKey('P_AG_QUERY', 'Query'));
            });
        }

        function init(cid, machineList, index) {
            allMachineGroups = machineList
            indexInEdit = index;

            if (allMachineGroups) {
                OnEdit();
            } else {
                machineGroupID = undefined;
                if (grid_dtsm != null) {
                    grid_dtsm.setData([]);
                }
                OnAdd();
            }
        }

        function OnAdd() {
            machineGroupID = undefined;
            $('#dialog_groupname').val('');
            $('#dialog_description').val('');
            $('#dialog_groupcode').val('');

            $("#btnPrevious").hide();
            $("#btnNext").hide();

            $('#selectedmachinelist input[type="checkbox"]').prop('checked', false);

            $('#dialog_groupname').focus();
        }

        function OnEdit() {
            var group = allMachineGroups[indexInEdit].Values;
            if (!group) {
                return;
            }

            machineGroupID = group.Id;

            $('#dialog_groupname').val(group.Name);
            $('#dialog_description').val(group.Description);
            $('#dialog_groupcode').val(group.Code);
            grid_dtsm.setData([]);

            $('#selectedmachinelist input[type="checkbox"]').prop('checked', false);

            if (allMachineGroups.length <= 1) {
                $("#btnPrevious").hide();
                $("#btnNext").hide();
            }
            else {
                $("#btnPrevious").show();
                $("#btnNext").show();
            }

            // 加载用户信息
            queryGroupMachines();
        }

        function OnNext() {
            OnSave(0, gotoNext);
        }

        function gotoNext() {
            if (++indexInEdit > allMachineGroups.length - 1)
                indexInEdit = 0;

            OnEdit();
            window.parent.changeGridSelectIndex(indexInEdit);
        }

        function OnPrevious() {
            OnSave(0, gotoPrevious);
        }

        function gotoPrevious() {
            if (--indexInEdit < 0)
                indexInEdit = allMachineGroups.length - 1;

            OnEdit();
            window.parent.changeGridSelectIndex(indexInEdit);
        }


        function OnSave(exit, callback) {
            var item = {
                'Name': $.trim($('#dialog_groupname').val()),
                'Description': $.trim($('#dialog_description').val()),
                'Code': $.trim($('#dialog_groupcode').val())
            };
            var alerttitle;
            if (machineGroupID) {
                item.Id = machineGroupID;
                alerttitle = GetTextByKey("P_AG_EDITASSETGROUP", "Edit Asset Group");
            } else {
                item.Id = "";
                alerttitle = GetTextByKey("P_AG_ADDASSETGROUP", "Add Asset Group");
            }

            if (!item.Name || item.Name.length == 0) {
                showAlert(GetTextByKey("P_AG_GROUPNAMECANNOTBEEMPTY", 'Group Name cannot be empty.'), alerttitle);
                $('#dialog_groupname').focus();
                return;
            }

            if (allMachineGroups != null) {
                for (var i = 0; i < allMachineGroups.length; i++) {
                    var group = allMachineGroups[i]
                    if (group.Name === item.Name && group.Id !== item.Id) {
                        showAlert(GetTextByKey("P_AG_NAMEALREADYEXISTS", 'Group Name already exists.'), alerttitle);
                        return;
                    }
                }
            }

            item.Assets = [];
            if (grid_dtsm.innerSource != []) {
                for (var i = 0; i < grid_dtsm.innerSource.length; i++) {
                    var mid = grid_dtsm.innerSource[i].Values.ID;
                    if (mid) {
                        item.Assets.push(mid);
                    }
                }
            }

            showloading(true);
            var param = JSON.stringify(item);
            param = htmlencode(param);
            devicerequest("SaveAssetGroup", param, function (data) {
                showloading(false);
                if (data.substring(0, 6) === 'Failed') {
                    showAlert(data, alerttitle);
                } else {
                    needRefreshDataOnCancel = true;
                    machineGroupID = data;

                    if (callback) {
                        //showAlert("Saved successfully.", 'Save Asset');
                        if (allMachineGroups != null) {
                            allMachineGroups[indexInEdit].Values = item;
                        }
                        callback(item);
                    } else {
                        if (exit == 0)
                            showAlert(GetTextByKey("P_AG_SAVSUCCESSFULLY", "Saved successfully."), GetTextByKey("P_AG_SAVASSETGROUP", 'Save Asset Group'));
                        else if (exit == 1)
                            OnExit(exit);
                    }
                }
            }, function (err) {
                showloading(false);
                showAlert(GetTextByKey("P_AG_FAILEDTOSAVEASSETGROUP", 'Failed to save Asset Group.'), GetTextByKey("P_AG_SAVASSETGROUP", 'Save Asset Group'));
            });
        }


        /************************** Machine********************************/
        /*************************************************************************/

        //var _selectedMachines = [];

        function queryGroupMachines() {
            devicerequest('GetAssetsByGroup', machineGroupID, function (data) {
                var grpMachines = data || [];

                //_selectedMachines = grpMachines;
                showSelectedMachine(grpMachines);

                $('#dialog_groupname').focus();
            }, function (err) {
                showAlert(GetTextByKey("P_AG_FAILEDLOADASSETS", 'Failed to load Asset(s).'), GetTextByKey("P_AG_EDITASSETGROUP", 'Edit Asset Group'));
            });
        }

        function showSelectedMachine(data) {
            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                var fr = { Values: r };
                rows.push(fr);
            }

            grid_dtsm.setData(rows);
        }

        function OnDelete(item) {
            showConfirm(GetTextByKey("P_AG_REMOVETHISASSET", "Are you sure you want to remove this asset:{0}?").replace('{0}', item.Name), GetTextByKey("P_AG_EDITGROUPASSETS", 'Edit Group Assets'), function () {
                for (var i = 0; i < grid_dtsm.innerSource.length; i++) {
                    var s = grid_dtsm.innerSource[i].Values;
                    if (s.ID === item.ID) {
                        grid_dtsm.innerSource.splice(i, 1);
                        break;
                    }
                }
                if (grid_dtsm.source != null) {
                    for (var j = 0; j < grid_dtsm.source.length; j++) {
                        if (item.ID === grid_dtsm.source[j].Values.ID) {
                            grid_dtsm.source.splice(j, 1);
                            break;
                        }
                    }
                }
                grid_dtsm.reload();
            });
        }

        function OnGroupsDelete() {
            showConfirm(GetTextByKey("P_AG_REMOVESELECTEDASSETS", 'Are you sure you want to remove these selected assets?'), GetTextByKey("P_AG_EDITGROUPASSETS", 'Edit Group Assets'), function () {
                for (var i = grid_dtsm.innerSource.length - 1; i >= 0; i--) {
                    var s = grid_dtsm.innerSource[i].Values;
                    if (s.selected) {
                        grid_dtsm.innerSource.splice(i, 1);
                    }
                }
                if (grid_dtsm.source != null) {
                    for (var j = grid_dtsm.source.length - 1; j >= 0; j--) {
                        var l = grid_dtsm.source[j].Values;
                        if (l.selected) {
                            grid_dtsm.source.splice(j, 1);
                        }
                    }
                }
                grid_dtsm.reload();
            });
        }

        function OnGroupsAdd() {
            showmaskbg(true);
            dialogAssets.exceptSource = grid_dtsm.innerSource.map(function (s) {
                return s.Values.ID;
            });
            dialogAssets.showSelector();
            $('#mask_bg').css('height', '100%');
        }

        var grid_dtsm;
        function InitGridSelectedMachines() {
            grid_dtsm = new GridView('#selectedmachinelist');
            grid_dtsm.lang = {
                all: GetTextByKey("P_GRID_ALL", "(All)"),
                ok: GetTextByKey("P_GRID_OK", "OK"),
                reset: GetTextByKey("P_GRID_RESET", "Reset")
            };
            var list_columns = [
                { name: 'VIN', caption: GetTextByKey("P_AG_VIN", "VIN"), valueIndex: 'VIN', css: { 'width': 170, 'text-align': 'left' } },
                { name: 'Name', caption: GetTextByKey("P_AG_NAME", "Name"), valueIndex: 'Name', css: { 'width': 170, 'text-align': 'left' } },
                { name: 'TypeName', caption: GetTextByKey("P_AG_TYPE", "Type"), valueIndex: 'TypeName', css: { 'width': 170, 'text-align': 'left' } }
            ];
            var columns = [
                {
                    // checkbox
                    name: 'check',
                    key: 'selected',
                    width: 30,
                    align: 'center',
                    sortable: false,
                    allcheck: true,
                    type: 3
                }
            ];
            // head
            for (var hd in list_columns) {
                var col = {};
                col.name = list_columns[hd].name;
                col.caption = list_columns[hd].caption;
                col.visible = true;
                col.sortable = true;
                col.width = list_columns[hd].css.width;
                col.align = list_columns[hd].css["text-align"]
                col.key = list_columns[hd].valueIndex;
                col.allowFilter = col.name === 'TypeName';
                col.styleFilter = function (item) {
                    if (item.Highlight)
                        return { 'background-color': 'yellow' };
                }
                columns.push(col);
            }
            columns.push({
                name: 'delete',
                width: 30,
                align: 'center',
                sortable: false,
                isurl: true,
                text: '\uf00d',
                events: {
                    onclick: function () {
                        OnDelete(this);
                    }
                },
                classFilter: function (e) {
                    return "icon-col";
                },
                attrs: { 'title': GetTextByKey("P_AG_DELETE", 'Delete') }
            });
            grid_dtsm.canMultiSelect = true;
            grid_dtsm.columns = columns;
            grid_dtsm.init();

            grid_dtsm.selectedrowchanged = function (rowindex) {
                var rowdata = grid_dtsm.source[rowindex];
                if (rowdata) {
                }
            }
        }


        /**************************End Machine********************************/
        /*****************************************************************************/

        function OnExit(type) {
            if (type === 0) {
                if (needRefreshDataOnCancel) {
                    type = 1;
                    needRefreshDataOnCancel = false;
                }
            }
            window.parent.CloseDialog(type);
        }

        var dialogAssets;
        $(function () {
            InitGridSelectedMachines();

            dialogAssets = new $assetselector('dialog_machines');
            dialogAssets.allowhidden = false;
            dialogAssets.onDialogClosed = function () {
                showmaskbg(false);
            };
            dialogAssets.onOK = function (source) {
                var items = [];
                for (var i = 0; i < source.length; i++) {
                    var it = source[i].Values;
                    if (it.Selected) {
                        items.push({
                            Values: {
                                ID: it.Id,
                                VIN: it.VIN,
                                Name: it.Name,
                                TypeName: it.TypeName
                            }
                        });
                    }
                }
                showmaskbg(false);
                grid_dtsm.setData(grid_dtsm.innerSource.concat(items));
            };

            window.parent.Opened();
        });

    </script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="dialog_machinegroup">
        <div id="mask_bg1" style="display: none;">
            <div class="loading c-spin"></div>
        </div>
        <div id="div_content">
            <div id="dialogmask" class="maskbg" style="display: none; z-index: 500;">
                <div class="loading_icon icon c-spin"></div>
            </div>
            <div class="function_title">
                <span class="sbutton iconsave" onclick="OnSave(0);" data-lgid="P_AG_SAVE">Save</span>
                <span class="sbutton iconsave" onclick="OnSave(1);" data-lgid="P_AG_SAVE1">Save and Exit</span>
                <span class="sbutton iconexit" onclick="OnExit(0);" data-lgid="P_AG_SAVE2">Exit Without Saving</span>
                <%--<span class="sbutton iconprevious" id="btnNext" onclick="OnPrevious();">Previous</span>--%>
                <%--<span class="sbutton iconnext" id="btnPrevious" onclick="OnNext();">Next</span>--%>
            </div>
            <div class="clear"></div>
            <div id="divcontent" class="assetcontent">
                <table class="group_table">
                    <tr>
                        <td class="label" data-lgid="P_AG_GROUPNAME_COLON">Group Name:</td>
                        <td>
                            <input type="text" id="dialog_groupname" class="inputbox" maxlength="200" tabindex="1" style="width: 300px;" />
                        </td>
                    </tr>
                    <tr>
                        <td class="label" style="width: 50px; text-align: right;" data-lgid="P_AG_CODE_COLON">Code:</td>
                        <td>
                            <input type="text" id="dialog_groupcode" class="inputbox" maxlength="50" tabindex="1" style="width: 300px;" />
                        </td>
                    </tr>
                    <tr>
                        <td class="label" data-lgid="P_AG_DESCRIPTION_COLON">Description:</td>
                        <td>
                            <textarea id="dialog_description" class="inputbox" maxlength="1000" tabindex="2" style="width: 300px"></textarea></td>
                    </tr>
                </table>
                <div class="dialog-subheader">
                    <span data-lgid="P_AG_GROUPASSETS">Group Assets</span>
                    <span class="sbutton icondelete" onclick="OnGroupsDelete()" style="float: right" data-lgid="P_AG_DELETE">Delete</span>
                    <span class="sbutton iconadd" onclick="OnGroupsAdd()" style="float: right" data-lgid="P_AG_ADD">Add</span>
                </div>

                <table id="tab_groupmachine" class="group_table" style="margin-top: 6px">
                    <tbody>
                        <tr>
                            <td style="width: 380px;">
                                <div id="selectedmachinelist" style="height: 484px; border-bottom: 1px solid #aaa;"></div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div id="mask_bg" style="display: none;">
            <div class="loading c-spin"></div>
        </div>
    </div>
</asp:Content>