@{
    ViewData["MainNum"] = "2";
    ViewData["SubNum"] = "2";
    ViewData["Title"] = "設備管理";
}

<div class="container-fluid">
    <div class="row flex-nowrap wrapper">
        <div class="col-md-2 col-1 pl-0 pr-0 collapse width border-right sidebar vh-100 overflow-auto">

            <div class="list-group border-0 card text-center text-md-left" id="sidebar">

                <div class="border bg-light rounded-top">
                    <div class="form-group p-2 m-0 rounded-top">
                        <input type="text" class="form-control form-control-lg shadow-inset-2 m-0" id="js_list_accordion_filter" placeholder="">
                    </div>
                    <div id="js_list_accordion" class="accordion accordion-hover accordion-clean js-list-filter">
                    </div>
                    <span class="filter-message js-filter-message"></span>
                </div>
            </div>
        </div>
        <div class="col-auto px-0">
            <a href="javascript:;" id="collapse" data-target=".sidebar" data-toggle="collapse" class="btn btn-default btn-xs btn-icon waves-effect waves-themed" style="border-radius: 0;" aria-expanded="true">
                <span class="collapsed-reveal"><i class="fal fa-angle-left fa-lg py-3"></i></span>
                <span class="collapsed-hidden"><i class="fal fa-angle-right fa-lg py-3"></i></span>
            </a>
        </div>

        <main class="col px-5 pl-md-2 main">
            <ol class="breadcrumb page-breadcrumb">
                <li class="breadcrumb-item"><a href="javascript:void(0);">首頁</a></li>
                <li class="breadcrumb-item">設備管理</li>
                <li class="breadcrumb-item active">設備管理</li>
                <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
            </ol>
            <div class="subheader">
                <h1 class="subheader-title">
                    <i class="subheader-icon fal fa-crosshairs"></i> <span id="select-main-system-name"></span> - <span id="select-sub-system-name"></span>
                </h1>
            </div>

            <div class="row">
                <div class="col-xl-12">
                    <div id="panel-5" class="panel">
                        <div class="panel-container show">
                            <div class="panel-content">
                                <div class="mb-5 d-flex align-items-center justify-content-start ">
                                    <span class="mr-2" style="font-size:18px">樓層</span>
                                    <div class="floor-panel-wrap">
                                    </div>
                                </div>

                                <div class="mb-5">
                                    <div class="card p-3 w-100">
                                        <div class="row">
                                            <div class="col-12">
                                                <div class="row mb-2">
                                                    <h3 class="mr-2">當前模式:</h3>
                                                    <h3 class="font-weight-bolder mr-2" id="floor-map-mode-text">檢視模式</h3>
                                                    @*<div class="edit-mode" id="floor-map-edit-mode-btn-wrap" style="display:none">
                                                            <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="CancelFloorMapEdit()">取消</button>
                                                            <button type="button" class="btn btn-primary waves-effect waves-themed" onclick="SaveFloorMapEdit()">確定</button>
                                                        </div>*@
                                                </div>
                                            </div>
                                            <div class="col-12 mb-2" id="floor_map" style="height : 50vh!important;">
                                            </div>
                                            <div class="col-12">
                                                <div class="edit-mode" id="floor-map-edit-mode-btn-wrap" style="display:none">
                                                    <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="CancelFloorMapEdit()">取消</button>
                                                    <button type="button" class="btn btn-primary waves-effect waves-themed" onclick="SaveFloorMapEdit()">確定</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="mb-5">
                                    <div class="card p-3 w-100">
                                        <div class="card-header d-flex align-items-center flex-wrap">
                                            <div class="card-title">
                                                設備基本資料
                                            </div>
                                            <div class="ml-auto">
                                                <a href="javascript:;" class="btn btn-success waves-effect waves-themed" id="addDevice-btn" onclick="AddDevice()"><span class="fal fa-plus mr-1"></span>新增設備</a>
                                                <a href="javascript:;" class="btn btn-primary waves-effect waves-themed" id="device-master-list-btn" style="display:none"><span class="fal fa-plus mr-1"></span>分電盤</a>
                                            </div>
                                        </div>
                                        <div class="card-body row">
                                            <div class="col-12">
                                                <!-- datatable start -->
                                                <table id="device_info_table" class="table table-bordered table-hover m-0 text-center">
                                                    <thead class="thead-themed">
                                                        <tr>
                                                            <th></th>
                                                            <th>序</th>
                                                            <th>棟別</th>
                                                            <th>系統大類</th>
                                                            <th>系統小類</th>
                                                            <th>樓層</th>
                                                            <th>設備編號</th>
                                                            <th>設備名稱</th>
                                                            <th>地圖座標</th>
                                                            <th>防災類別</th>
                                                            <th>功能</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="mb-5">
                                    <div class="card p-3 w-100">
                                        <div class="card-header d-flex align-items-center flex-wrap">
                                            <div class="card-title">
                                                設備種類設定
                                            </div>
                                        </div>
                                        <div class="card-body row">
                                            <div class="col-12">
                                                <!-- datatable start -->
                                                <table id="device_kind_table" class="table table-bordered table-hover m-0 text-center">
                                                    <thead class="thead-themed">
                                                        <tr>
                                                            <th>序</th>
                                                            <th>設備機型</th>
                                                            <th>設備icon</th>
                                                            <th>正常狀態</th>
                                                            <th>關機狀態</th>
                                                            <th>異常狀態</th>
                                                            <th>功能</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Modal 設備基本資料(新增) -->
<div class="modal fade" id="device-info-add-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    設備基本資料 - 新增
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3 align-items-center justify-content-start">
                    <div class="col-12">
                        <div class="row mb-2 align-items-center justify-content-start">
                            <span class="col-1">棟別</span>
                            <div class="col-11 row">
                                <div id="import-temp-building-tag-list" class="col-12">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="row mb-2 align-items-center justify-content-start">
                            <span class="col-1">系統別</span>
                            <div class="col-11 row align-items-start">
                                <div id="import-temp-system-tag-list" class="col-12">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="row mb-2 align-items-center justify-content-start">
                            <span class="col-1">樓層</span>
                            <div class="col-11 row align-items-start">
                                <div id="import-temp-floor-tag-list" class="col-12">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="row mb-2 d-flex align-items-center justify-content-start">
                            <span class="col-1">設備種類</span>
                            <div class="col-11 row align-items-start">
                                <div id="import-temp-name-tag-list" class="col-12">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-12 row">
                        <div class="col-12">
                            <!-- datatable start -->
                            <table id="device_import_check_temp_table" class="table table-bordered table-hover m-0 text-center">
                                <thead class="thead-themed">
                                    <tr>
                                        <th>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="select-all-device-number">
                                                <label class="custom-control-label" for="select-all-device-number">全選</label>
                                            </div>
                                        </th>
                                        <th>序</th>
                                        <th>設備編號</th>
                                        <th>設備名稱</th>
                                        <th>防災類別</th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-device-add-btn" onclick="SaveDeviceAdd()">確定</button>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /.Modal 設備基本資料(新增) -->
<!-- Modal 設備基本資料(修改) -->
<div class="modal fade" id="device-info-edit-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    設備基本資料 - 修改
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <form class="device-info-edit-form" id="device-info-edit-form">
                    <div class="row">
                        <div class="form-group col-6">
                            <label class="form-label" for="device_building_name_modal">棟別</label><br>
                            <span id="device_building_name_modal" class="fw-900"></span>
                        </div>
                        <div class="form-group col-6">
                            <label class="form-label" for="system_main_code_modal">系統大類</label><br>
                            <span id="device_main_system_name_modal" class="fw-900"></span>
                        </div>
                        <div class="form-group col-6">
                            <label class="form-label" for="system_main_code_modal">系統小類</label><br>
                            <span id="device_sub_system_name_modal" class="fw-900"></span>
                        </div>
                        <div class="form-group col-6">
                            <label class="form-label" for="system_main_code_modal">樓層</label><br>
                            <span id="device_floor_name_modal" class="fw-900"></span>
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="device_number_modal"><span class="text-danger">*</span>設備編號</label><br>
                            <span id="device_number_modal" class="fw-900"></span>
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="device_name_modal"><span class="text-danger">*</span>設備名稱</label>
                            <input type="text" id="device_name_modal" name="device_name_modal" class="form-control">
                        </div>
                        <div class="form-group col-12" id="device-coordinate-wrap">
                            <label class="form-label" for="device_coordinate_modal"><span class="text-danger">*</span>地圖座標</label>
                            <div class="row">
                                <div class="col-6">
                                    <label class="form-label" for="device_coordinate_x_modal">x:</label>
                                    <input type="number" step="0.001" id="device_coordinate_x_modal" name="device_coordinate_x_modal" class="form-control">
                                </div>
                                <div class="col-6">
                                    <label class="form-label" for="device_coordinate_y_modal">y:</label>
                                    <input type="number" step="0.001" id="device_coordinate_y_modal" name="device_coordinate_y_modal" class="form-control">
                                </div>
                            </div>
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="device_disaster_modal">防災類別</label>
                            <div class="row ml-2 mr-1" id="disaster_check">

                            </div>
                        </div>
                        <div class="form-group col-8" id="device-ip-wrap">
                            <label class="form-label" for="device_ip_modal">設備IP</label>
                            <input type="text" id="device_ip_modal" name="device_ip_modal" class="form-control">
                        </div>
                        <div class="form-group col-4" id="device-port-wrap">
                            <label class="form-label" for="device_port_modal">設備Port</label>
                            <input type="text" id="device_port_modal" name="device_port_modal" class="form-control">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="SaveDeviceInfoEdit()">確定</button>
            </div>
        </div>
    </div>
</div>
<!-- /.Modal 設備基本資料(修改) -->
<!-- Modal 設備種類資料 -->
<div class="modal fade" id="device-kind-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    設備種類 - 修改
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <form class="device-kind-form" id="device-kind-form">
                    <div class="row">
                        <div class="form-group col-12">
                            <label class="form-label" for="device_kind_name_modal">設備機型</label><br>
                            <span id="device_kind_name_modal" class="fw-900"></span>
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="device_image_modal">設備icon</label>
                            <input type="file" id="device_image_modal" name="device_image_modal" class="form-control" accept="image/*">
                        </div>
                        <div class="form-group col-12">
                            <div class="row">
                                <div class="col-2 d-flex justify-content-center align-items-center">
                                    <div class="form-group">
                                        <label class="form-label">燈號 1</label>
                                    </div>
                                </div>
                                <div class="col row">
                                    <div class="form-group col">
                                        <label class="form-label" for="device_normal_text_modal">顯示文字</label>
                                        <input type="text" id="device_normal_text_modal" name="device_normal_text_modal" class="form-control" placeholder="正常/開機/運作中" maxlength="50" />
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_normal_point_name_modal">點位名稱</label>
                                        <select class="form-control" id="device_normal_point_name_modal">
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_normal_point_col_modal">點位欄位</label>
                                        <select class="form-control" id="device_normal_point_col_modal" disabled>
                                            <option value="" selected disabled>未選擇</option>
                                            <option value="Facets_key">Facets_key</option>
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_normal_point_value_modal">點位值</label>
                                        <select class="form-control" id="device_normal_point_value_modal" disabled>
                                            <option value="" selected disabled>未選擇</option>
                                            <option value="trueText">trueText</option>
                                            <option value="falseText">falseText</option>
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_normal_color_modal">燈號</label>
                                        <input type="text" id="device_normal_color_modal" name="device_normal_color_modal" class="form-control" placeholder="#123456" maxlength="7" />
                                    </div>
                                    <div class="form-group col d-flex align-items-center" style="display: none !important">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" id="device_normal_flashing_modal" name="device_normal_flashing_modal" class="custom-control-input" value="1">
                                            <label class="custom-control-label" for="device_normal_flashing_modal">是否閃爍</label>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div class="row">
                                <div class="col-2 d-flex justify-content-center align-items-center">
                                    <div class="form-group">
                                        <label class="form-label">燈號 2</label>
                                    </div>
                                </div>
                                <div class="col row">
                                    <div class="form-group col">
                                        <label class="form-label" for="device_close_text_modal">顯示文字</label>
                                        <input type="text" id="device_close_text_modal" name="device_close_text_modal" class="form-control" placeholder="關機/非運作" maxlength="50" />
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_close_point_name_modal">點位名稱</label>
                                        <select class="form-control" id="device_close_point_name_modal">
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_close_point_col_modal">點位欄位</label>
                                        <select class="form-control" id="device_close_point_col_modal" disabled>
                                            <option value="" selected disabled>未選擇</option>
                                            <option value="Facets_key">Facets_key</option>
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_close_point_value_modal">點位值</label>
                                        <select class="form-control" id="device_close_point_value_modal" disabled>
                                            <option value="" selected disabled>未選擇</option>
                                            <option value="trueText">trueText</option>
                                            <option value="falseText">falseText</option>
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label class="form-label" for="device_close_color_modal">燈號</label>
                                        <input type="text" id="device_close_color_modal" name="device_close_color_modal" class="form-control" placeholder="#123456" maxlength="7" />
                                    </div>
                                    <div class="form-group col d-flex align-items-center" style="display:none !important">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" id="device_close_flashing_modal" name="device_close_flashing_modal" class="custom-control-input" value="1">
                                            <label class="custom-control-label" for="device_close_flashing_modal">是否閃爍</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-12">
                                    <div class="row">
                                        <div class="col-2 d-flex justify-content-center align-items-center">
                                            <div class="form-group">
                                                <label class="form-label">異常燈號</label>
                                            </div>
                                        </div>
                                        <div class="col">
                                            <div class="row">
                                                <div class="form-group col">
                                                    <label class="form-label" for="device_error_text_modal">顯示文字</label>
                                                    <input type="text" id="device_error_text_modal" name="device_error_text_modal" class="form-control" placeholder="異常" maxlength="50" />
                                                </div>
                                                <div class="form-group col">
                                                    <label class="form-label" for="device_error_point_name_modal">點位名稱</label>
                                                    <select class="form-control" id="device_error_point_name_modal">
                                                    </select>
                                                </div>
                                                <div class="form-group col">
                                                    <label class="form-label" for="device_error_point_col_modal">點位欄位</label>
                                                    <select class="form-control" id="device_error_point_col_modal" disabled>
                                                        <option value="" selected disabled>未選擇</option>
                                                        <option value="Facets_key">Facets_key</option>
                                                    </select>
                                                </div>
                                                <div class="form-group col">
                                                    <label class="form-label" for="device_error_point_value_modal">點位值</label>
                                                    <select class="form-control" id="device_error_point_value_modal" disabled>
                                                        <option value="" selected disabled>未選擇</option>
                                                        <option value="trueText">trueText</option>
                                                        <option value="falseText">falseText</option>
                                                    </select>
                                                </div>
                                                <div class="form-group col">
                                                    <label class="form-label" for="device_error_color_modal">燈號</label>
                                                    <input type="text" id="device_error_color_modal" name="device_error_color_modal" class="form-control" placeholder="#123456" maxlength="7" />
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="form-group col d-flex flex-column justify-content-center">
                                                    <div class="custom-control custom-checkbox">
                                                        <input type="checkbox" id="device_error_flashing_modal" name="device_error_flashing_modal" class="custom-control-input" value="1">
                                                        <label class="custom-control-label" for="device_error_flashing_modal">是否閃爍</label>
                                                    </div>
                                                    <div class="custom-control custom-checkbox" style="display:none">
                                                        <input type="checkbox" id="device_error_independent_modal" name="device_error_independent_modal" class="custom-control-input" value="1">
                                                        <label class="custom-control-label" for="device_error_independent_modal">是否獨立顯示</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="save-device-kind-btn" onclick="SaveDeviceKind()">確定</button>
            </div>
        </div>
    </div>
</div>
<!-- /.Modal 設備種類資料 -->
<!-- Modal 設備子節點資料 -->
<div class="modal fade" id="device-node-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    設備子節點 - 修改
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <form class="device-node-form" id="device-node-form">
                    <div class="row">
                        <div class="form-group col-12">
                            <label class="form-label" for="device_node_name_modal"><span class="text-danger">*</span>設備子節點名稱</label><br>
                            <input type="text" id="device_node_name_modal" name="device_node_name_modal" class="form-control">
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="device_node_coordinate_modal"><span class="text-danger">*</span>地圖座標</label>
                            <div class="row">
                                <div class="col-6">
                                    <label class="form-label" for="device_node_coordinate_x_modal">x:</label>
                                    <input type="number" step="0.001" id="device_node_coordinate_x_modal" name="device_node_coordinate_x_modal" class="form-control">
                                </div>
                                <div class="col-6">
                                    <label class="form-label" for="device_node_coordinate_y_modal">y:</label>
                                    <input type="number" step="0.001" id="device_node_coordinate_y_modal" name="device_node_coordinate_y_modal" class="form-control">
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="SaveDeviceNode()">確定</button>
            </div>
        </div>
    </div>
</div>
<!-- /.Modal 設備子節點資料 -->
<!-- Modal 設備Master list -->
<div class="modal fade" id="device-master-list-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    分電盤列表
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <table id="device_master_table" class="table table-bordered table-hover m-0 text-center">
                    <thead class="thead-themed">
                        <tr>
                            <th>序</th>
                            <th>分電盤編號</th>
                            <th>分電盤名稱</th>
                            <th>分電盤icon</th>
                            <th>功能</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<!-- /.Modal 設備Master list -->
<!-- Modal 編輯 設備Master -->
<div class="modal fade" id="device-master-edit-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    編輯分電盤
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <form class="device-master-form" id="device-master-form">
                    <div class="row">
                        <div class="form-group col-12">
                            <label class="form-label" for="device_master_number_modal">分電盤編號</label><br>
                            <span id="device_master_number_modal" class="fw-900"></span>
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="device_master_full_name_modal">分電盤名稱</label>
                            <input type="text" id="device_master_full_name_modal" name="device_master_full_name_modal" class="form-control">
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label" for="device_master_icon_modal">設備icon</label>
                            <input type="file" id="device_master_icon_modal" name="device_master_icon_modal" class="form-control" accept="image/*">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="save-device-master-btn" onclick="SaveDeviceMaster()">確定</button>
            </div>
        </div>
    </div>
</div>
<!-- /.Modal 編輯 設備Master -->


@section Scripts {
    <script src="~/js/echarts.min.js"></script>
    <script>
        var buildingCollapses;
        var selected_building_menu = {}, selected_floor_tag;
        var chartDom, myChart, option,
            floor_map_mode = "view", //平面圖當前模式
            selected_temp_device, //被選擇要修改的設備
            temp_device_on_floor_map = [] //暫存在地圖上新的位置;
        var currentData = [];
        var deviceInfoTable, selected_device_guid;
        var deviceImportCheckTempTable,
            deviceImportCheckTempFilterList = [],
            selected_building_tag = "",
            selected_system_tag = "",
            selected_floor_tag = "",
            selected_name_tag = "";
        var selected_device_node_guid;
        var selected_device_parents_collapses = [];
        var deviceKindTable,
            selected_device_kind_guid,
            selected_device_building_tag,
            selected_device_system_tag,
            selected_device_floor_tag,
            selected_device_name_tag;
        var deviceMasterTable,
            selected_device_master_guid;
        $(function () {
            $('#collapse').trigger("click");

            //預設載入左方選單列表
            GetBuildingMenuCollapse("");

            //修改左方選單列表查詢條件
            $("#js_list_accordion_filter").change(function (e) {
                GetBuildingMenuCollapse($(this).val());
            });

            chartDom = document.getElementById("floor_map");
            myChart = echarts.init(chartDom, null, { width: 'auto', });

            $('.sidebar').on("shown.bs.collapse", function () {
                setTimeout(function () {
                    myChart.resize();
                }, 500);
            });

            $('.sidebar').on("hidden.bs.collapse", function () {
                setTimeout(function () {
                    myChart.resize();
                }, 500);
            });

            //#region 設備基本資料DataTable
            deviceInfoTable = $("#device_info_table").DataTable({
                "pageLength": 20,
                "columns": [
                    {
                        "className": 'dt-control',
                        "orderable": false,
                        "data": null,
                        "defaultContent": '<i class="fal fa-plus"></i>'
                    },
                    {
                        "data": null,
                        "render": function (data, type, row, meta) {
                            return meta.row + 1;
                        }
                    },
                    {
                        "data": "building_full_name"
                    },
                    {
                        "data": "main_system_full_name"
                    },
                    {
                        "data": "sub_system_full_name"
                    },
                    {
                        "data": "floor_full_name"
                    },
                    {
                        "data": "device_number"
                    },
                    {
                        "data": "device_full_name"
                    },
                    {
                        "data": "device_coordinate"
                    },
                    {
                        "data": "device_disaster_type_text"
                    },
                    {
                        "data": null,
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).empty();
                            if (rowData != null && (rowData.device_system_category_layer3 == "L1" || rowData.device_system_category_layer3 == "L2")) {
                                $(td).html(`
                                        <button class="btn btn-primary edit-btn">修改</button>
                                        <button class="btn btn-info add-device-node-btn">加入子節點</button>
                                        <button class="btn btn-danger del-btn">刪除</button>`)
                            } else {
                                $(td).html(`<button class="btn btn-primary edit-btn">修改</button> <button class="btn btn-danger del-btn">刪除</button>`)
                            }

                        },
                        @*"defaultContent": '<button class="btn btn-primary edit-btn">修改</button> <button class="btn btn-danger del-btn">刪除</button>'*@
                    }
                ],
                "order": [[1, "asc"]],
                'createdRow': function (row, data, dataIndex) {
                    $(row).attr('id', "tr_" + data.device_guid);
                    $(row).attr('data-guid', data.device_guid);
                },
                "columnDefs": [
                    {
                        'targets': 0,
                        'searchable': false,
                        'visible': false
                    },
                    {
                        'targets': 8,
                        'searchable': false,
                        'className': 'dt-body-center',
                        'createdCell': function (td, cellData, rowData, row, col) {
                            $(td).empty();

                            if (cellData != null) {
                                var coordinate = cellData.split(',')

                                $(td).append(`<span>x:${parseFloat(coordinate[0])}, y:${parseFloat(coordinate[1])}</span><br>`);
                                $(td).append(`<a href="javascript:void(0)" class="device-coordinate-btn">修改座標</a>`);
                            } else {
                                $(td).append('<button class="btn btn-primary device-coordinate-btn">定位座標</button>');
                            }
                        }
                    }
                ],
                //"order": [[2, "desc"]],
                "ajax": {
                    "url": "/DeviceManage/DeviceTableList",
                    "type": "POST",
                    "data": function (d) {
                    d.building_tag = selected_building_menu.building_tag ? selected_building_menu.building_tag : "";
                        d.device_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.main_system_tag : "";
                        d.device_name_tag = selected_building_menu.main_system ? selected_building_menu.main_system.sub_system ? selected_building_menu.main_system.sub_system.sub_system_tag : "" : "";
                        d.device_floor_tag = selected_floor_tag ? selected_floor_tag : "";
                    },
                    "dataSrc": function (rel) {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                            return;
                        }

                        currentData = rel.data;

                        currentData = $.map(currentData, function (item) {

                            if (item.device_system_category_layer3 == "L1" || item.device_system_category_layer3 == "L2") {
                                //照明設備
                                $("#device-master-list-btn").show();
                                deviceInfoTable.column(0).visible(true); //點擊顯示子節點
                                deviceInfoTable.column(8).visible(false); //設備座標
                            } else {
                                $("#device-master-list-btn").hide();
                                deviceInfoTable.column(0).visible(false);  //點擊顯示子節點
                                deviceInfoTable.column(8).visible(true); //設備座標
                            }


                            item.selected = false;
                            if (item.device_coordinate != undefined && item.device_coordinate != null) {
                                var coordinate = item.device_coordinate.split(',')
                                item.value = [
                                    parseFloat(coordinate[0]),
                                    parseFloat(coordinate[1])
                                ]
                            }

                            if (item.device_nodes != undefined && item.device_nodes != null && item.device_nodes.length > 0) {
                                $.map(item.device_nodes, function (item_node) {
                                    item_node.selected = false;
                                    if (item_node.device_node_coordinate != undefined && item_node.device_node_coordinate != null) {
                                        var node_coordinate = item_node.device_node_coordinate.split(',')
                                        item_node.value = [
                                            parseFloat(node_coordinate[0]),
                                            parseFloat(node_coordinate[1])
                                        ]
                                    }
                                });
                            }

                            return item;
                        });

                        if (currentData == null || currentData.length == 0) {
                            this.currentData = [];
                        }
                        if (myChart.getOption() && myChart.getOption().geo && myChart.getOption().geo.length > 0) {
                            resetData();
                        }

                        return currentData;
                    }
                }
            });
            //#endregion

            deviceInfoTable.on('draw', function () {
                $.each(selected_device_parents_collapses, function (i, id) {
                    var tr = $(`#${id}`)
                    var row = deviceInfoTable.row(tr);
                    if (!row.child.isShown()) {
                        $(`#${id}`).find("td.dt-control").trigger('click');
                    }

                });
            });

            //#region 編輯設備
            $('#device_info_table').on("click", "button.edit-btn", function () {

                selected_device_guid = $(this).parents('tr').attr('data-guid');

                //取得災害類別
                var url_disaster = "/DeviceManage/GetDisasterList";
                $.post(url_disaster, null, function (rel) {
                    if (rel.code != "0000") {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                        }
                        else {
                            toast_warning(rel.msg);
                        }
                        return;
                    }
                    else {

                        var checkbox = "";
                        $('#disaster_check').empty();
                        $.each(rel.data, function (index, val) {
                            checkbox += '<div class="col-3 mb-2 custom-control custom-checkbox align-content-center">';
                            checkbox += '<input type="checkbox" class="custom-control-input" name="selectDisaster[]"  id="' + val.system_value + '" value="' + val.system_value + '" />';
                            checkbox += '<label class="custom-control-label" for="' + val.system_value + '">' + val.system_key + '</label>';
                            checkbox += '</div>';
                        });
                        $('#disaster_check').append(checkbox);

                        //取得單一設備基本資料
                        var url = "/DeviceManage/GetOneDevice";

                        var send_data = {
                            guid: selected_device_guid
                        }

                        $.post(url, send_data, function (rel) {
                            console.log(rel);

                            if (rel.code != "0000") {
                                if (rel.code == "9999") {
                                    toast_error(rel.msg);
                                }
                                else {
                                    toast_warning(rel.msg);
                                }
                                return;
                            }
                            else {
                                $("#device_building_name_modal").html(rel.data.building_full_name);
                                $("#device_main_system_name_modal").html(rel.data.main_system_full_name);
                                $("#device_sub_system_name_modal").html(rel.data.sub_system_full_name);
                                $("#device_floor_name_modal").html(rel.data.floor_full_name);
                                $("#device_number_modal").html(rel.data.device_number);

                                $("#device_name_modal").val(rel.data.device_full_name);

                                if (rel.data.device_system_category_layer3 == "L1" || rel.data.device_system_category_layer3 == "L2") {
                                    $("#device-coordinate-wrap").hide();
                                } else {
                                    $("#device-coordinate-wrap").show();

                                    if (rel.data.device_coordinate != undefined && rel.data.device_coordinate != null) {
                                        var coordinate = rel.data.device_coordinate.split(',')

                                        $("#device_coordinate_x_modal").val(coordinate[0]);
                                        $("#device_coordinate_y_modal").val(coordinate[1]);
                                    } else {
                                        $("#device_coordinate_x_modal").val("");
                                        $("#device_coordinate_y_modal").val("");
                                    }
                                }

                                rel.data.device_disasters.forEach(function (item, index) {
                                    $(`input[name="selectDisaster[]"][value="${item.device_system_value}"]`).prop("checked", true)
                                });

                                if (rel.data.device_system_category_layer3 != "C") {
                                    $("#device-ip-wrap").hide();
                                    $("#device-port-wrap").hide();
                                }
                                else {
                                    $("#device-ip-wrap").show();
                                    $("#device-port-wrap").show();

                                    $("#device_ip_modal").val(rel.data.device_ip);
                                    $("#device_port_modal").val(rel.data.device_port);
                                }

                                $("#device-info-edit-modal").modal();
                            }
                        }, 'json');
                    }
                });
            });
            //#endregion

            //#region 刪除設備
            $('#device_info_table').on("click", "button.del-btn", function () {

                selected_device_guid = $(this).parents('tr').attr('data-guid');

                Swal.fire(
                    {
                        title: "刪除",
                        text: "你確定是否刪除此筆資料?",
                        type: "warning",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: "是",
                        cancelButtonText: "否"
                    }).then(function (result) {
                        if (result.value) {
                            var url = "/DeviceManage/DeleteOneDevice";
                            var send_data = {
                                Guid: selected_device_guid
                            }
                            $.post(url, send_data, function (rel) {
                                if (rel.code != "0000") {
                                    if (rel.code == "9999") {
                                        toast_error(rel.msg);
                                    }
                                    else {
                                        toast_warning(rel.msg);
                                    }
                                    return;
                                }
                                else {
                                    toast_ok(rel.msg);
                                    deviceInfoTable.ajax.reload(null, false);
                                    return;
                                }

                            }, 'json');
                        }
                    });
            });
            //#endregion

            //#region 編輯設備定位座標
            $('#device_info_table').on("click", ".device-coordinate-btn", function () {

                if ($(this).attr("disabled")) {
                    return;
                }

                selected_device_guid = $(this).parents('tr').attr('data-guid');
                var index = currentData.findIndex(function (item) { return item.device_guid === selected_device_guid });

                currentData[index].selected = true;

                selected_temp_device = currentData[index];

                ChangeFloorMapMode("edit");
            });
            //#endregion

            //#region 編輯設備防災類別
            $('#disaster_check').on("click", 'input[type="checkbox"]', function () {

                var checked = $(this).val();

                //console.log($('#disaster_check').find('input:checkbox:checked').length)
                if ($('#disaster_check').find('input:checkbox:checked').length != 0) {
                    $('input[name="selectDisaster[]"]').prop('checked', false);
                    $('input[name="selectDisaster[]"]').map(function (index, item) {
                        var item_value = $(item).val();

                        if (item_value == checked) {
                            $(item).prop('checked', true)
                        }
                    });
                }


                
            });
            //#endregion

            //#region 設備Master DataTable
            deviceMasterTable = $("#device_master_table").DataTable({
                "columns": [
                    {
                        "data": null,
                        "render": function (data, type, row, meta) {
                            return meta.row + 1;
                        }
                    },
                    {
                        "data": "device_master_number",
                        "render": function (data, type, row, meta) {
                            if (data != undefined && data != null && data != "") {
                                return data;
                            } else {
                                return row.device_building_tag + "_" + row.device_name_tag;
                            }
                        }
                    },
                    {
                        "data": "device_master_full_name"
                    },
                    {
                        "data": "device_master_icon",
                        "render": function (data, type, row, meta) {
                            if (row.device_master_icon == undefined || row.device_master_icon == null || row.device_master_icon == '') {
                                return "";
                            }
                            var html = `<img src="/upload/device_icon/${row.device_master_icon}" style="margin: auto; width:30px;">
                                        </img>`;
                            return html;
                        }
                    },
                    {
                        "data": null,
                        "defaultContent": '<button class="btn btn-primary edit-btn">修改</button>'
                    }
                ],
                'createdRow': function (row, data, dataIndex) {
                    $(row).attr('data-guid', data.device_master_guid);
                    $(row).attr('data-device-building-tag', data.device_building_tag);
                    $(row).attr('data-device-name-tag', data.device_name_tag);
                },
                //"order": [[2, "desc"]],
                "ajax": {
                    "url": "/DeviceManage/GetDeviceMasterTableList",
                    "type": "POST",
                    "data": function (d) {
                        d.Building_tag = selected_building_menu.building_tag ? selected_building_menu.building_tag : "";
                        d.Main_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.main_system_tag : "";
                        d.Sub_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.sub_system ? selected_building_menu.main_system.sub_system.sub_system_tag : "" : "";
                        d.Floor_tag = selected_floor_tag ? selected_floor_tag : "";
                    },
                    "dataSrc": function (rel) {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                            return;
                        }

                        data = rel.data;

                        if (data == null || data.length == 0) {
                            this.data = [];
                        }

                        return data;
                    }
                }
            });
            //#endregion

            //#region 分電盤按鈕
            $("#device-master-list-btn").click(function (e) {
                e.preventDefault();

                var selectedBuilding_tag = selected_building_menu.building_tag ? selected_building_menu.building_tag : "";
                var selectedMain_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.main_system_tag : "";
                var selectedSub_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.sub_system ? selected_building_menu.main_system.sub_system.sub_system_tag : "" : "";
                var selectedFloor_tag = selected_floor_tag ? selected_floor_tag : "";
                if (selectedBuilding_tag == '' || selectedMain_system_tag == '' || selectedSub_system_tag == '' || selectedFloor_tag == '') {
                    toast_warning("請先選擇系統類別及樓層。");
                    return;
                }

                //取得設備master列表
                deviceMasterTable.ajax.reload(null, false);
                $("#device-master-list-modal").modal();
            });
            //#endregion

            //#region 編輯設備master
            $('#device_master_table').on("click", "button.edit-btn", function () {

                selected_device_master_guid = $(this).parents('tr').attr('data-guid');
                selected_device_building_tag = $(this).parents('tr').attr('data-device-building-tag');
                selected_device_system_tag = "";
                selected_device_floor_tag = "";
                selected_device_name_tag = $(this).parents('tr').attr('data-device-name-tag');
                selected_device_master_number_txt = $(this).parents('tr')[0].children[1].innerText

                //取得單一設備基本資料
                var url = "/DeviceManage/GetOneDeviceMaster";

                var send_data = {
                    guid: selected_device_master_guid
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                        }
                        else {
                            toast_warning(rel.msg);
                        }
                        return;
                    }
                    else {
                        $("#device_master_number_modal").html(selected_device_master_number_txt);
                        if (rel.data != undefined && rel.data != null) {
                            $("#device_master_full_name_modal").val(rel.data.device_master_full_name);
                        }

                        $("#device-master-edit-modal").modal();
                    }
                }, 'json');
            });
            //#endregion

            //#region 展開子節點列表
            $('#device_info_table').on("click", "td.dt-control", function () {

                var tr = $(this).closest('tr');
                var row = deviceInfoTable.row(tr);

                var index = $.inArray(tr.attr('id'), selected_device_parents_collapses)

                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                    tr.find("td").first().html(`<i class="fal fa-plus"></i>`);

                    selected_device_parents_collapses.splice(index, 1);
                }
                else {
                    // Open this row
                    console.log(row.data());
                    row.child(DeviceNodeFormat(row.data().device_nodes)).show();
                    tr.addClass('shown');
                    tr.find("td").first().html(`<i class="fal fa-minus"></i>`);

                    if (index < 0) {
                        selected_device_parents_collapses.push(tr.attr('id'))
                    }

                }
            });
            //#endregion

            //#region 子節點表格樣式
            function DeviceNodeFormat(device_nodes) {
                var tbody_content = "";

                device_nodes.forEach(function (item, index) {
                    var coordinate_html = "";
                    if (item.device_node_coordinate != null) {
                        var coordinate = item.device_node_coordinate.split(',')
                        coordinate_html += `<span>x:${parseFloat(coordinate[0])}, y:${parseFloat(coordinate[1])}</span><br>
                                        <a href="javascript:void(0)" class="device-node-coordinate-btn">修改座標</a>`;
                    } else {
                        coordinate_html += `<button class="btn btn-primary device-node-coordinate-btn">定位座標</button>`;
                    }

                    tbody_content += `
                                        <tr data-device-node-guid="${item.device_node_guid}" data-device-guid="${item.device_guid}">
                                            <td>
                                                ${index + 1}
                                            </td>
                                            <td>
                                                ${item.device_node_full_name}
                                            </td>
                                            <td>
                                                ${coordinate_html}
                                            </td>
                                            <td>
                                                <button class="btn btn-primary edit-node-btn">修改</button>
                                                <button class="btn btn-danger del-node-btn">刪除</button>
                                            </td>
                                        </tr>
                                    `;
                });

                var html = "";
                html = `<table class="table table-bordered table-hover m-0 text-center device-node-table">
                            <thead class="thead-themed">
                                <tr>
                                    <th>序</th>
                                    <th>名稱</th>
                                    <th>座標</th>
                                    <th>功能</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${tbody_content}
                            </tbody>
                        </table>`;

                return html;
            }
            //#endregion

            //#region 加入子節點
            $('#device_info_table').on("click", "button.add-device-node-btn", function () {

                selected_device_guid = $(this).parents('tr').attr('data-guid');
                selected_device_node_guid = "";

                $("#device-node-form").trigger("reset");
                $("#device-node-modal").modal();
            });
            //#endregion

            //#region 編輯子節點
            $('#device_info_table').on("click", ".device-node-table button.edit-node-btn", function () {

                selected_device_node_guid = $(this).parents('tr').attr('data-device-node-guid');
                selected_device_guid = $(this).parents('tr').attr('data-device-guid');

                //取得單一設備子節點資料
                var url = "/DeviceManage/GetOneDeviceNode";

                var send_data = {
                    guid: selected_device_node_guid
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                        }
                        else {
                            toast_warning(rel.msg);
                        }
                        return;
                    }
                    else {
                        $("#device_node_name_modal").val(rel.data.device_node_full_name);

                        if (rel.data.device_node_coordinate != undefined && rel.data.device_node_coordinate != null) {
                            var coordinate = rel.data.device_node_coordinate.split(',')

                            $("#device_node_coordinate_x_modal").val(coordinate[0]);
                            $("#device_node_coordinate_y_modal").val(coordinate[1]);
                        } else {
                            $("#device_node_coordinate_x_modal").val("");
                            $("#device_node_coordinate_y_modal").val("");
                        }

                        $("#device-node-modal").modal();
                    }
                }, 'json');
            });
            //#endregion

            //#region 編輯子節點定位座標
            $('#device_info_table').on("click", ".device-node-table .device-node-coordinate-btn", function () {

                if ($(this).attr("disabled")) {
                    return;
                }

                selected_device_guid = $(this).parents('tr').attr('data-device-guid');
                selected_device_node_guid = $(this).parents('tr').attr('data-device-node-guid');
                var index = currentData.findIndex(function (item) { return item.device_guid === selected_device_guid });

                var node_index = currentData[index].device_nodes.findIndex(function (item) { return item.device_node_guid === selected_device_node_guid });

                selected_temp_device = currentData[index].device_nodes[node_index];

                ChangeFloorMapMode("edit");
            });
            //#endregion

            //#region 刪除子節點
            $('#device_info_table').on("click", ".device-node-table button.del-node-btn", function () {

                selected_device_node_guid = $(this).parents('tr').attr('data-device-node-guid');

                Swal.fire(
                    {
                        title: "刪除",
                        text: "你確定是否刪除此筆資料?",
                        type: "warning",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: "是",
                        cancelButtonText: "否"
                    }).then(function (result) {
                        if (result.value) {
                            var url = "/DeviceManage/DeleteOneDeviceNode";
                            var send_data = {
                                Guid: selected_device_node_guid
                            }
                            $.post(url, send_data, function (rel) {
                                if (rel.code != "0000") {
                                    if (rel.code == "9999") {
                                        toast_error(rel.msg);
                                    }
                                    else {
                                        toast_warning(rel.msg);
                                    }
                                    return;
                                }
                                else {
                                    toast_ok(rel.msg);
                                    deviceInfoTable.ajax.reload(null, false);
                                    return;
                                }

                            }, 'json');
                        }
                    });
            });
            //#endregion

            //#region 設備種類DataTable
            deviceKindTable = $("#device_kind_table").DataTable({
                "columns": [
                    {
                        "data": null,
                        "render": function (data, type, row, meta) {
                            return meta.row + 1;
                        }
                    },
                    {
                        "data": "device_name_tag"
                    },
                    {
                        "data": "device_image",
                        "render": function (data, type, row, meta) {
                            if (row.device_image == undefined || row.device_image == null || row.device_image == '') {
                                return "";
                            }
                            var file_names = row.device_image.split(".");
                            var html = `<img src="/upload/device_icon/${row.device_image}" style="margin: auto; width:45px; height: auto">
                                        </img>`;
                            return html;
                        }
                    },
                    {
                        "data": "device_normal_color",
                        "render": function (data, type, row, meta) {

                            var device_normal_text = row.device_normal_text ? row.device_normal_text : "";
                            var device_normal_point_name = row.device_normal_point_name ? row.device_normal_point_name : "";
                            var device_normal_point_col = row.device_normal_point_col ? row.device_normal_point_col : "";
                            var device_normal_point_value = row.device_normal_point_value ? row.device_normal_point_value : "";
                            var device_normal_color = row.device_normal_color ? row.device_normal_color : "";
                            var flashing = row.device_normal_flashing == 1 ? "是" : "否";

                            var full_point_arr = [];
                            if (device_normal_point_name != "") {
                                full_point_arr.push(device_normal_point_name)
                            }
                            if (device_normal_point_col != "") {
                                full_point_arr.push(device_normal_point_col)
                            }
                            if (device_normal_point_value != "") {
                                full_point_arr.push(device_normal_point_value)
                            }

                            var html = `
                                        <div class="row">
                                            <label class="col-12">${device_normal_text}</label>
                                        </div>
                                        <div class="row">
                                            <label class="col-12">${full_point_arr.join("-")}</label>
                                        </div>
                                        <div class="row">
                                            <div style="width: 30px;height: 30px; margin:auto; border-radius: 50%;background-color: ${device_normal_color}"></div>
                                        </div>
                                        @*<div class="row">
                                            <label class="col-8">是否閃爍:</label>
                                            <label class="col-4">${flashing}</label>
                                        </div>*@
                                        `;
                            return html;
                        }
                    },
                    {
                        "data": "device_close_color",
                        "render": function (data, type, row, meta) {

                            var device_close_text = row.device_close_text ? row.device_close_text : "";
                            var device_close_point_name = row.device_close_point_name ? row.device_close_point_name : "";
                            var device_close_point_col = row.device_close_point_col ? row.device_close_point_col : "";
                            var device_close_point_value = row.device_close_point_value ? row.device_close_point_value : "";
                            var device_close_color = row.device_close_color ? row.device_close_color : "";
                            var flashing = row.device_normal_flashing == 1 ? "是" : "否";

                            var full_point_arr = [];
                            if (device_close_point_name != "") {
                                full_point_arr.push(device_close_point_name)
                            }
                            if (device_close_point_col != "") {
                                full_point_arr.push(device_close_point_col)
                            }
                            if (device_close_point_value != "") {
                                full_point_arr.push(device_close_point_value)
                            }

                            var html = `
                                        <div class="row">
                                            <label class="col-12">${device_close_text}</label>
                                        </div>
                                        <div class="row">
                                            <label class="col-12">${full_point_arr.join("-")}</label>
                                        </div>
                                        <div class="row">
                                            <div style="width: 30px;height: 30px; margin:auto; border-radius: 50%;background-color: ${device_close_color}"></div>
                                        </div>
                                        @*<div class="row">
                                            <label class="col-8">是否閃爍:</label>
                                            <label class="col-4">${flashing}</label>
                                        </div>*@
                                        `;
                            return html;
                        }
                    },
                    {
                        "data": "device_error_color",
                        "render": function (data, type, row, meta) {

                            var device_error_text = row.device_error_text ? row.device_error_text : "";
                            var device_error_point_name = row.device_error_point_name ? row.device_error_point_name : "";
                            var device_error_point_col = row.device_error_point_col ? row.device_error_point_col : "";
                            var device_error_point_value = row.device_error_point_value ? row.device_error_point_value : "";
                            var device_error_color = row.device_error_color ? row.device_error_color : "";
                            var flashing = row.device_error_flashing == 1 ? "是" : "否";
                            var independent = row.device_error_independent == 1 ? "是" : "否";

                            var full_point_arr = [];
                            if (device_error_point_name != "") {
                                full_point_arr.push(device_error_point_name)
                            }
                            if (device_error_point_col != "") {
                                full_point_arr.push(device_error_point_col)
                            }
                            if (device_error_point_value != "") {
                                full_point_arr.push(device_error_point_value)
                            }

                            var html = `
                                        <div class="row">
                                            <label class="col-12">${device_error_text}</label>
                                        </div>
                                        <div class="row">
                                            <label class="col-12">${full_point_arr.join("-")}</label>
                                        </div>
                                        <div class="row">
                                            <div style="width: 30px;height: 30px; margin:auto; border-radius: 50%;background-color: ${device_error_color}"></div>
                                        </div>
                                        <div class="row">
                                            <label class="col-8">是否閃爍:</label>
                                            <label class="col-4">${flashing}</label>
                                        </div>
                                        @*<div class="row">
                                            <label class="col-8">是否獨立顯示:</label>
                                            <label class="col-4">${independent}</label>
                                        </div>*@
                                        `;
                            return html;
                        }
                    },
                    {
                        "data": null,
                        "defaultContent": '<button class="btn btn-primary edit-btn">修改</button>'
                    }
                ],
                'createdRow': function (row, data, dataIndex) {
                    $(row).attr('data-guid', data.device_kind_guid);
                    $(row).attr('data-device-building-tag', data.device_building_tag);
                    $(row).attr('data-device-system-tag', data.device_system_tag);
                    $(row).attr('data-device-floor-tag', data.device_floor_tag);
                    $(row).attr('data-device-name-tag', data.device_name_tag);
                },
                //"order": [[2, "desc"]],
                "ajax": {
                    "url": "/DeviceManage/DeviceKindTableList",
                    "type": "POST",
                    "data": function (d) {
                        d.building_tag = selected_building_menu.building_tag ? selected_building_menu.building_tag : "";
                        d.device_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.main_system_tag : "";
                        d.device_name_tag = selected_building_menu.main_system ? selected_building_menu.main_system.sub_system ? selected_building_menu.main_system.sub_system.sub_system_tag : "" : "";
                        //d.Floor_tag = selected_floor_tag ? selected_floor_tag : "";
                    },
                    "dataSrc": function (rel) {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                            return;
                        }

                        data = rel.data;

                        if (data == null || data.length == 0) {
                            this.data = [];
                        }

                        return data;
                    }
                }
            });
            //#endregion

            //#region 編輯設備種類
            $('#device_kind_table').on("click", "button.edit-btn", function () {

                selected_device_kind_guid = $(this).parents('tr').attr('data-guid');
                selected_device_building_tag = $(this).parents('tr').attr('data-device-building-tag');
                selected_device_system_tag = $(this).parents('tr').attr('data-device-system-tag');
                selected_device_floor_tag = $(this).parents('tr').attr('data-device-floor-tag');
                selected_device_name_tag = $(this).parents('tr').attr('data-device-name-tag');
                selected_device_name_tag_txt = $(this).parents('tr')[0].children[1].innerText

                //取得單一設備基本資料
                var url = "/DeviceManage/GetOneDeviceKind";

                var send_data = {
                    guid: selected_device_kind_guid
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                        }
                        else {
                            toast_warning(rel.msg);
                        }
                        return;
                    }
                    else {
                        device_kind_data = rel.data;

                        //取得單一設備基本資料
                        var selectedSub_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.sub_system ? selected_building_menu.main_system.sub_system.sub_system_tag : "" : "";
                        var url = "/DeviceManage/GetDeviceItem";
                        var send_data = {
                            sub_system_tag: selectedSub_system_tag
                        }

                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                if (rel.code == "9999") {
                                    toast_error(rel.msg);
                                }
                                else {
                                    toast_warning(rel.msg);
                                }
                                return;
                            }
                            else {
                                $('#device_image_modal').val("");

                                $("#device_normal_point_name_modal").empty();
                                $("#device_close_point_name_modal").empty();
                                $("#device_error_point_name_modal").empty();
                                $("#device_normal_point_name_modal").append($("<option />").val("").text("未選擇"));
                                $("#device_close_point_name_modal").append($("<option />").val("").text("未選擇"));
                                $("#device_error_point_name_modal").append($("<option />").val("").text("未選擇"));
                                $.each(rel.data, function (index, val) {
                                    $("#device_normal_point_name_modal").append($("<option />").val(val.id).text(val.points));
                                    $("#device_close_point_name_modal").append($("<option />").val(val.id).text(val.points));
                                    $("#device_error_point_name_modal").append($("<option />").val(val.id).text(val.points));
                                });


                                $("#device_kind_name_modal").html(selected_device_name_tag_txt);
                                if (device_kind_data != null) {
                                    $("#device_normal_text_modal").val(device_kind_data.device_normal_text ? device_kind_data.device_normal_text : "");

                                    var normal_point_name = device_kind_data.device_normal_point_guid ? device_kind_data.device_normal_point_guid : "";
                                    var normal_point_col = device_kind_data.device_normal_point_col ? device_kind_data.device_normal_point_col : "";
                                    var normal_point_value = device_kind_data.device_normal_point_value ? device_kind_data.device_normal_point_value : "";

                                    $("#device_normal_point_name_modal").val(normal_point_name);
                                    $("#device_normal_point_col_modal").val(normal_point_col);
                                    $("#device_normal_point_value_modal").val(normal_point_value);
                                    if (normal_point_name != undefined && normal_point_name != null) {
                                        var normal_point_text = $("#device_normal_point_name_modal option:selected").text();
                                        if (normal_point_name == "" || normal_point_text == "ER") {
                                            $("#device_normal_point_col_modal").val("").attr("disabled", true);
                                            $("#device_normal_point_value_modal").val("").attr("disabled", true);
                                        } else {
                                            $("#device_normal_point_col_modal").val(normal_point_col).attr("disabled", false);
                                            $("#device_normal_point_value_modal").val(normal_point_value).attr("disabled", false);
                                        }
                                    } else {
                                        $("#device_normal_point_col_modal").val("").attr("disabled", true);
                                        $("#device_normal_point_value_modal").val("").attr("disabled", true);
                                    }

                                    $("#device_normal_color_modal").val(device_kind_data.device_normal_color ? device_kind_data.device_normal_color : "");

                                    if (device_kind_data.device_name_tag != undefined && device_kind_data.device_name_tag != null && device_kind_data.device_normal_flashing == 1) {
                                        $("#device_normal_flashing_modal").prop("checked", true);
                                    }
                                    else {
                                        $("#device_normal_flashing_modal").prop("checked", false);
                                    }

                                    $("#device_close_text_modal").val(device_kind_data.device_close_text ? device_kind_data.device_close_text : "");

                                    var close_point_name = device_kind_data.device_close_point_guid ? device_kind_data.device_close_point_guid : "";
                                    var close_point_col = device_kind_data.device_close_point_col ? device_kind_data.device_close_point_col : "";
                                    var close_point_value = device_kind_data.device_close_point_value ? device_kind_data.device_close_point_value : "";

                                    $("#device_close_point_name_modal").val(close_point_name);
                                    $("#device_close_point_col_modal").val(close_point_col);
                                    $("#device_close_point_value_modal").val(close_point_value);
                                    if (close_point_name != undefined && close_point_name != null) {
                                        var close_point_text = $("#device_close_point_name_modal option:selected").text();
                                        if (close_point_name == "" || close_point_text == "ER") {
                                            $("#device_close_point_col_modal").val("").attr("disabled", true);
                                            $("#device_close_point_value_modal").val("").attr("disabled", true);
                                        } else {
                                            $("#device_close_point_col_modal").val(close_point_col).attr("disabled", false);
                                            $("#device_close_point_value_modal").val(close_point_value).attr("disabled", false);
                                        }
                                    } else {
                                        $("#device_close_point_col_modal").val("").attr("disabled", true);
                                        $("#device_close_point_value_modal").val("").attr("disabled", true);
                                    }

                                    $("#device_close_color_modal").val(device_kind_data.device_close_color ? device_kind_data.device_close_color : "");

                                    if (device_kind_data.device_name_tag != undefined && device_kind_data.device_name_tag != null && device_kind_data.device_close_flashing == 1) {
                                        $("#device_close_flashing_modal").prop("checked", true);
                                    }
                                    else {
                                        $("#device_close_flashing_modal").prop("checked", false);
                                    }

                                    $("#device_error_text_modal").val(device_kind_data.device_error_text ? device_kind_data.device_error_text : "");

                                    var error_point_name = device_kind_data.device_error_point_guid ? device_kind_data.device_error_point_guid : "";
                                    var error_point_col = device_kind_data.device_error_point_col ? device_kind_data.device_error_point_col : "";
                                    var error_point_value = device_kind_data.device_error_point_value ? device_kind_data.device_error_point_value : "";
                                    $("#device_error_point_name_modal").val(error_point_name);
                                    $("#device_error_point_col_modal").val(error_point_col);
                                    $("#device_error_point_value_modal").val(error_point_value);
                                    if (error_point_name != undefined && error_point_name != null) {
                                        var error_point_text = $("#device_error_point_name_modal option:selected").text();
                                        if (error_point_name == "" || error_point_text == "ER") {
                                            $("#device_error_point_col_modal").val("").attr("disabled", true);
                                            $("#device_error_point_value_modal").val("").attr("disabled", true);
                                        } else {
                                            $("#device_error_point_col_modal").val(error_point_col).attr("disabled", false);
                                            $("#device_error_point_value_modal").val(error_point_value).attr("disabled", false);
                                        }
                                    } else {
                                        $("#device_error_point_col_modal").val("").attr("disabled", true);
                                        $("#device_error_point_value_modal").val("").attr("disabled", true);
                                    }

                                    $("#device_error_color_modal").val(device_kind_data.device_error_color ? device_kind_data.device_error_color : "");

                                    if (device_kind_data.device_name_tag != undefined && device_kind_data.device_name_tag != null && device_kind_data.device_error_flashing == 1) {
                                        $("#device_error_flashing_modal").prop("checked", true);
                                    }
                                    else {
                                        $("#device_error_flashing_modal").prop("checked", false);
                                    }

                                    if (device_kind_data.device_name_tag != undefined && device_kind_data.device_name_tag != null && device_kind_data.device_error_independent == 1) {
                                        $("#device_error_independent_modal").prop("checked", true);
                                    }
                                    else {
                                        $("#device_error_independent_modal").prop("checked", false);
                                    }
                                }
                                else {
                                    //Reset Form
                                    $('#device_image_modal').val("");
                                    $('#device_normal_text_modal').val("");
                                    $('#device_normal_point_name_modal').val("");
                                    $('#device_normal_point_col_modal').val("");
                                    $('#device_normal_point_value_modal').val("");
                                    $('#device_normal_color_modal').val("");
                                    $('#device_normal_flashing_modal').prop("checked", false);

                                    $('#device_close_text_modal').val("");
                                    $('#device_close_point_name_modal').val("");
                                    $('#device_close_point_col_modal').val("");
                                    $('#device_close_point_value_modal').val("");
                                    $('#device_close_color_modal').val("");
                                    $('#device_close_flashing_modal').prop("checked", false);

                                    $('#device_error_text_modal').val("");
                                    $('#device_error_point_name_modal').val("");
                                    $('#device_error_point_col_modal').val("");
                                    $('#device_error_point_value_modal').val("");
                                    $('#device_error_color_modal').val("");
                                    $('#device_error_flashing_modal').prop("checked", false);
                                    $('#device_error_independent_modal').prop("checked", false);
                                }

                                $("#device-kind-modal").modal();
                            }
                        }, 'json')
                    }
                }, 'json');
            });
            //#endregion

            //#region 設備種類燈號判別
            $("#device_normal_point_name_modal").change(function () {
                var point_name_value = $(this).val();
                var point_name_text = $(this).find("option:selected").text();

                if (point_name_value == "" || point_name_text == "ER") {
                    $("#device_normal_point_col_modal").val("").attr("disabled", true);
                    $("#device_normal_point_value_modal").val("").attr("disabled", true);
                } else if (point_name_text != "ER") {
                    $("#device_normal_point_col_modal").attr("disabled", false);
                    $("#device_normal_point_value_modal").attr("disabled", false);
                    $("#device_close_point_name_modal").val(point_name_value).trigger("change");
                }
            });

            $("#device_close_point_name_modal").change(function () {
                var point_name_value = $(this).val();
                var point_name_text = $(this).find("option:selected").text();

                if (point_name_value == "" || point_name_text == "ER") {
                    $("#device_close_point_col_modal").val("").attr("disabled", true);
                    $("#device_close_point_value_modal").val("").attr("disabled", true);
                } else if (point_name_text != "ER") {
                    $("#device_close_point_col_modal").attr("disabled", false);
                    $("#device_close_point_value_modal").attr("disabled", false);
                    $("#device_normal_point_name_modal").val(point_name_value).trigger("change");
                }
            });

            $("#device_error_point_name_modal").change(function () {
                var point_name_value = $(this).val()
                var point_name_text = $(this).find("option:selected").text();

                if (point_name_value == "" || point_name_text == "ER") {
                    $("#device_error_point_col_modal").val("").attr("disabled", true);
                    $("#device_error_point_value_modal").val("").attr("disabled", true);
                } else if (point_name_text != "ER") {
                    $("#device_error_point_col_modal").attr("disabled", false);
                    $("#device_error_point_value_modal").attr("disabled", false);
                }
            });
            //#endregion

            //#region 新增設備基本資料DataTable
            deviceImportCheckTempTable = $("#device_import_check_temp_table").DataTable({
                "pageLength": 20,
                "columns": [
                    {
                        "data": null,
                    },
                    {
                        "data": null,
                        "render": function (data, type, row, meta) {
                            return meta.row + 1;
                        }
                    },
                    {
                        "data": "device_number"
                    },
                    {
                        "data": null,
                        "render": function (data, type, row, meta) {
                            return row.device_name_tag + '_' + row.device_serial_tag;
                        }
                    },
                    {
                        "data": "device_disaster_type_text",
                    },
                ],
                "columnDefs": [{
                    'targets': 0,
                    'searchable': false,
                    'orderable': false,
                    'className': 'dt-body-center',
                    'render': function (data, type, full, meta) {
                        var check_html = "";
                        check_html += `<div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="${data.device_number}" name="selectedDevice[]" value="${data.device_number}" data-system-category="${data.device_system_category_layer3}" data-device-disaster="${data.device_disasters}" />
                                            <label class="custom-control-label" for="${data.device_number}"/>
                                       </div>`;
                        return check_html;
                    }
                }],
                "order": [[1, "asc"]],
                "ajax": {
                    "url": "/DeviceManage/DeviceImportCheckTempTableList",
                    "type": "POST",
                    "data": function (d) {
                        d.Device_building_tag = selected_building_tag ? selected_building_tag : "";
                        d.Device_system_tag = selected_system_tag ? selected_system_tag : "";
                        d.Device_floor_tag = selected_floor_tag ? selected_floor_tag : "";
                        d.Device_name_tag = selected_name_tag ? selected_name_tag : "";
                    },
                    "dataSrc": function (rel) {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                            return;
                        }

                        data = rel.data;

                        if (data == null || data.length == 0) {
                            this.data = [];
                        }

                        return data;
                    }
                }
            });
            //#endregion

            //#region 新增設備基本資料全選
            $("#select-all-device-number").change(function () {

                var rows = deviceImportCheckTempTable.rows({ 'search': 'applied' }).nodes();

                if (this.checked) {
                    $('input[type="checkbox"]', rows).prop('checked', this.checked);
                } else {
                    $('input[type="checkbox"]', rows).prop('checked', this.checked);
                }
            });
            //#endregion
        });

        //#region 建置左側選單列表
        function GetBuildingMenuCollapse(filter) {
            var url = "/DeviceManage/GetBuildingMenuCollapse";

            var send_data = {
                Filter: filter
            }

            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    if (rel.code == "9999") {
                        toast_error(rel.msg);
                    }
                    else {
                        toast_warning(rel.msg);
                    }
                    return;
                }
                else {
                    buildingCollapses = rel.data;

                    $("#js_list_accordion").empty();

                    if (buildingCollapses == undefined && buildingCollapses.length <= 0) {
                        $('#js_list_accordion').append("<div>查無結果</div>");
                    }

                    var html = '';

                    buildingCollapses.forEach(function (buildingCollapse, buildingCollapse_index) {
                        html += `
                                    <div class="card border-top-left-radius-0 border-top-right-radius-0">
                                        <div class="card-header">
                                            <a href="javascript:void(0);" class="card-title collapsed" data-toggle="collapse" data-target="#js_list_accordion-${buildingCollapse_index}" aria-expanded="false" data-filter-tags="settings">
                                                <i class="fal fa-globe width-2 fs-xl"></i>
                                                ${buildingCollapse.full_name}
                                                <span class="ml-auto">
                                                    <span class="collapsed-reveal">
                                                        <i class="fal fa-chevron-up fs-xl"></i>
                                                    </span>
                                                    <span class="collapsed-hidden">
                                                        <i class="fal fa-chevron-down fs-xl"></i>
                                                    </span>
                                                </span>
                                            </a>
                                        </div>
                                        <div id="js_list_accordion-${buildingCollapse_index}" class="collapse" data-parent="#js_list_accordion" style="">`;

                        buildingCollapse.main_systems.forEach(function (main_system, main_system_index) {
                            html += `
                                            <div id="cp-${main_system_index}" class="card py-3">
                                                <div class="card-header pl-4 pr-3 d-flex justify-content-between">
                                                    <a href="javascript:;" class="" data-toggle="collapse" data-target="#cp-${main_system_index} > .card-body" aria-expanded="true">
                                                        <span class="collapsed-hidden"><h4 class="font-weight-bold"><i class="fal fa-charging-station"></i> ${main_system.full_name} <i class="fal fa-chevron-down fs-xl"></i></h4></span>
                                                        <span class="collapsed-reveal"><h4 class="font-weight-bold"><i class="fal fa-charging-station"></i> ${main_system.full_name} <i class="fal fa-chevron-up fs-xl"></i></h4></span>
                                                    </a>
                                                </div>
                                                <div class="card-body p-0 collapse show">
                                                    <div class="p-0">
                                                        <ul class="list-group list-group-flush">
                                        `;

                            main_system.sub_systems.forEach(function (sub_system, sub_Systems_index) {
                                html += `
                                                            <li class="list-group-item pr-0 d-flex justify-content-between">
                                                                <a href="javascript:;" onclick="ChangeFloorPanel(this)"
                                                                            data-building-tag="${buildingCollapse.building_tag}"
                                                                    data-main-system-tag="${main_system.main_system_tag}"
                                                                    data-sub-system-tag="${sub_system.sub_system_tag}">
                                                                    ${sub_system.full_name}
                                                                </a>
                                                            </li>`;
                            });

                            html += `
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>`;
                        });

                        html += `   </div>
                                    </div>`;
                    });

                    $('#js_list_accordion').append(html);

                    $("#js_list_accordion .collapse").collapse('show');

                    return;
                }

            }, 'json');
        }
        //#endregion

        //#region 變更樓層的控制面板
        function ChangeFloorPanel(dom) {

            var selected_target = {
                "building_tag": $(dom).attr("data-building-tag") ? $(dom).attr("data-building-tag") : "",
                "main_system_tag": $(dom).attr("data-main-system-tag") ? $(dom).attr("data-main-system-tag") : "",
                "sub_system_tag": $(dom).attr("data-sub-system-tag") ? $(dom).attr("data-sub-system-tag") : "",
            }

            buildingCollapses.forEach(function (building_item, building_index) {
                if (building_item.building_tag == selected_target.building_tag) {
                    selected_building_menu.building_tag = building_item.building_tag;
                    selected_building_menu.main_system = {};

                    building_item.main_systems.forEach(function (main_system_item, main_system_index) {
                        if (main_system_item.main_system_tag == selected_target.main_system_tag) {
                            selected_building_menu.main_system.main_system_tag = main_system_item.main_system_tag
                            selected_building_menu.main_system.sub_system = {};

                            $("#select-main-system-name").html(main_system_item.full_name);

                            main_system_item.sub_systems.forEach(function (sub_system_item, sub_system_index) {
                                if (sub_system_item.sub_system_tag == selected_target.sub_system_tag) {
                                    selected_building_menu.main_system.sub_system.sub_system_tag = sub_system_item.sub_system_tag
                                    selected_building_menu.main_system.sub_system.floors = sub_system_item.floors;

                                    $("#select-sub-system-name").html(sub_system_item.full_name);

                                    //匯入floor panel
                                    $(".floor-panel-wrap").empty();
                                    sub_system_item.floors.forEach(function (floor_item, floor_index) {
                                        $(".floor-panel-wrap").append(`<button type="button" class="btn btn-secondary waves-effect waves-themed mr-2 mb-2 btn-floor" onclick="ChangeDevicePanel(this)" data-floor-guid="${floor_item.floor_tag}">${floor_item.full_name}</button>`)
                                    });
                                }
                            });
                        }
                    });
                }
            });

            $(".btn-floor").first().click();
        }
        //#endregion

        //#region 變更平面圖與設備的控制面板
        function ChangeDevicePanel(dom) {

            selected_floor_tag = $(dom).attr("data-floor-guid") ? $(dom).attr("data-floor-guid") : ""

            var current_floor = selected_building_menu.main_system.sub_system.floors.filter(function (item) {
                return item.floor_tag == selected_floor_tag
            })[0];

            $.each($(".btn-floor"), function (index, item) {
                if ($(item).hasClass("btn-success")) {
                    $(item).removeClass("btn-success");
                    $(item).addClass("btn-secondary");
                }
            });

            $(dom).hasClass("btn-secondary") ? $(dom).removeClass("btn-secondary").addClass("btn-success") : $(dom).addClass("btn-success");

            deviceInfoTable.ajax.reload(null, false);
            deviceKindTable.ajax.reload(null, false);

            ChangeFloorMapMode("");

            //#region 平面圖設定
            myChart.clear();
            $.get(`/upload/floor_map/${current_floor.floor_map_name}.svg`, function (svg) {

                if (svg == undefined || svg == null) {
                    return;
                }

                echarts.registerMap('floor_svg', { svg: svg });

                option = {
                    // animationDurationUpdate: 1500,
                    tooltip: {
                        formatter: function (params) {
                            if (params.data.device_node_guid != undefined && params.data.device_node_guid != null && params.data.device_node_guid != "") {
                                return `名稱:${params.data.device_node_full_name}<br>
                                    Guid:${params.data.device_node_guid}`
                            }
                            else {
                                return `名稱:${params.data.device_full_name}<br>
                                    Guid:${params.data.device_guid}`
                            }
                        }
                    },
                    toolbox: { //工具欄
                        show: false
                    },
                    geo: {
                        map: 'floor_svg',
                        roam: true,
                        scaleLimit: {  //限制放大縮小倍數
                            max: 32,
                            min: 2.5
                        },
                        layoutSize: '100%',
                        layoutCenter: ['50%', '50%'],
                        zoom: 2.5,
                        silent: true
                    },
                    series: [
                        {   //不管有無被選擇(圓點)
                            type: 'scatter',
                            coordinateSystem: 'geo',
                            geoIndex: 0,
                            symbol: 'circle',
                            symbolSize: 10,
                            symbolOffset: [10, 10],
                            label: {
                                show: false
                            },
                            data: currentData,
                            z: 2
                        },
                        {   //未選擇的設備(icon)
                            type: 'scatter',
                            coordinateSystem: 'geo',
                            geoIndex: 0,
                            symbolSize: 30,
                            label: {
                                formatter: '{b}',
                                position: 'bottom',
                                show: true,
                                backgroundColor: 'orange'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '20',
                                    fontWeight: 'bold',
                                    color: 'yellow'
                                }
                            },
                            selectedMode: 'single',
                            data: null,
                            z: 1
                        },
                        {   //被選擇的設備(icon)
                            type: 'effectScatter',
                            coordinateSystem: 'geo',
                            geoIndex: 0,
                            showEffectOn: 'render',
                            symbolSize: 30,
                            label: {
                                formatter: '{b}',
                                position: 'bottom',
                                show: true,
                                backgroundColor: 'orange'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '20',
                                    fontWeight: 'bold',
                                    color: 'yellow'
                                }
                            },
                            selectedMode: 'single',
                            data: null,
                            z: 1
                        },
                        {   //編輯模式底下的設備(圓點,只會有一個)
                            type: 'scatter',
                            coordinateSystem: 'geo',
                            geoIndex: 0,
                            symbol: 'circle',
                            symbolSize: 10,
                            symbolOffset: [10, 10],
                            label: {
                                show: false
                            },
                            data: currentData,
                            z: 2
                        },
                        {   //編輯模式底下的設備(icon,只會有一個)
                            type: 'scatter',
                            coordinateSystem: 'geo',
                            geoIndex: 0,
                            symbolSize: 30,
                            label: {
                                formatter: '{b}',
                                position: 'bottom',
                                show: true,
                                backgroundColor: 'orange'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '20',
                                    fontWeight: 'bold',
                                    color: 'yellow'
                                }
                            },
                            data: null,
                            z: 1
                        },
                    ],
                };

                myChart.setOption(option);

                myChart.getZr().on('click', function (params) {
                    console.log("click", params);
                    var pixelPoint = [params.offsetX, params.offsetY];
                    var dataPoint = myChart.convertFromPixel({ geoIndex: 0 }, pixelPoint);
                    console.log(dataPoint);

                    if (floor_map_mode == "edit") {

                        temp_device_on_floor_map = [{
                            device_guid: selected_temp_device.device_guid,
                            device_full_name: selected_temp_device.device_full_name,
                            device_node_guid: selected_temp_device.device_node_guid ? selected_temp_device.device_node_guid : null,
                            device_node_full_name: selected_temp_device.device_node_full_name ? selected_temp_device.device_node_full_name : null,
                            status: selected_temp_device.status,
                            value: dataPoint
                        }];

                        resetData();
                    }


                    // currentData.push([dataPoint[0], dataPoint[1], 1]);
                    // myChart.setOption(option);
                });

                myChart.on('selectchanged', function (params) {
                    @*var pixelPoint = [params.offsetX, params.offsetY];
                    var dataPoint = myChart.convertFromPixel({ geoIndex: 0 }, pixelPoint);*@
                    console.log("selectchanged", params);
                    // currentData.push([dataPoint[0], dataPoint[1], 1]);
                    // myChart.setOption(option);

                    currentData = $.map(currentData, function (item) {
                        item.selected = false;
                        return item;
                    });

                    if (params.selected.length > 0) {
                        currentData[params.selected[0].seriesIndex - 1].selected = true;
                    }

                    resetData();
                });

                // myChart.getZr().on('mousewheel', function (params) {
                //     console.log(params)
                // })
                myChart.on('georoam', function (params) {
                    @*console.log("myChart", myChart)*@
                    @*console.log("myChart canvas Width Height", [myChart.getWidth(), myChart.getHeight()]);*@
                    @*console.log("params", params)
                    console.log("geo", myChart.getOption().geo[0])*@
                    var zoom = myChart.getOption().geo[0].zoom;

                    if (zoom <= 2.5) {
                        ResetFloorMap();
                        myChart.setOption({
                            geo: {
                                roam: 'scale'
                            },
                        });
                    } else {
                        myChart.setOption({
                            geo: {
                                roam: true
                            },
                        });
                    }

                    resetData();
                });
            })
            .fail(function () {
                toast_warning("查無該樓層地圖")
                myChart.clear();
            });
            //#endregion
        }
        //#endregion

        //#region 重設平面圖設備資料
        function resetData() {
            const scatter_symbol_unselect_convertData = function (data) { //不管有無被選擇(圓點)
                let res = [], temp = [];

                data.forEach(function (item, index) {
                    //如果有子節點,則只針對子節點操作
                    if (item.device_nodes != undefined && item.device_nodes != null && item.device_nodes.length > 0) {
                        item.device_nodes.forEach(function (item_node, item_node_index) {
                            temp.push(item_node);
                        });
                    } else {
                        temp.push(item)
                    }
                });

                temp.map(function (item) {

                    var obj = {
                        device_guid: item.device_guid,
                        device_full_name: item.device_full_name ? item.device_full_name : null,
                        device_node_guid: item.device_node_guid ? item.device_node_guid : null,
                        device_node_full_name: item.device_node_full_name ? item.device_node_full_name : null,
                        status: item.status,
                        value: item.value
                    }

                    obj.itemStyle = { 'color': "#0000FF" };
                    res.push(obj);

                });

                return res;
            }

            const scatter_icon_unselect_convertData = function (data) { //未選擇的設備(icon)
                let res = [], temp = [];

                data.forEach(function (item, index) {
                    //如果有子節點,則只針對子節點操作
                    if (item.device_nodes != undefined && item.device_nodes != null && item.device_nodes.length > 0) {
                        item.device_nodes.forEach(function (item_node, item_node_index) {
                            if (item_node.selected != undefined && item_node.selected != null && item_node.selected == false) {
                                //添加父節點相關資訊
                                item_node.device_image_url = item.device_image_url;
                                temp.push(item_node);
                            }
                        });
                    } else {
                        if (item.selected == false) {
                            temp.push(item)
                        }
                    }
                });

                temp.map(function (item) {

                    var obj = {
                        device_guid: item.device_guid,
                        device_full_name: item.device_full_name ? item.device_full_name : null,
                        device_node_guid: item.device_node_guid ? item.device_node_guid : null,
                        device_node_full_name: item.device_node_full_name ? item.device_node_full_name : null,
                        symbol: 'image://' + item.device_image_url,
                        status: item.status,
                        value: item.value
                    }

                    obj.itemStyle = { 'color': "#0000FF" };
                    res.push(obj);
                });

                return res;
            }

            const effectScatter_icon_selected_convertData = function (data) { //被選擇的設備(icon)
                let res = [], temp = [];

                data.forEach(function (item, index) {
                    //如果有子節點,則只針對子節點操作
                    if (item.device_nodes != undefined && item.device_nodes != null && item.device_nodes.length > 0) {
                        item.device_nodes.forEach(function (item_node, item_node_index) {
                            if (item_node.selected != undefined && item_node.selected != null && item_node.selected == true) {
                                //添加父節點相關資訊
                                item_node.device_image_url = item.device_image_url;
                                temp.push(item_node);
                            }
                        });
                    } else {
                        if (item.selected == true) {
                            temp.push(item)
                        }
                    }
                });

                temp.map(function (item) {

                    var obj = {
                        device_guid: item.device_guid,
                        device_full_name: item.device_full_name ? item.device_full_name : null,
                        device_node_guid: item.device_node_guid ? item.device_node_guid : null,
                        device_node_full_name: item.device_node_full_name ? item.device_node_full_name : null,
                        symbol: 'image://' + item.device_image_url,
                        status: item.status,
                        value: item.value
                    }

                    obj.itemStyle = { 'color': "#0000FF" };
                    res.push(obj);
                });

                return res;
            }

            const scatter_symbol_temp_device = function (data) { //編輯模式底下的設備(圓點,只會有一個)
                let res = [];
                data.map(function (item) {

                    var obj = {
                        device_guid: item.device_guid,
                        device_full_name: item.device_full_name,
                        status: item.status,
                        value: item.value
                    }

                    switch (item.status) {
                        case 0:
                            obj.itemStyle = { 'color': item.device_close_color };
                            break;
                        case 1:
                            obj.itemStyle = { 'color': item.device_normal_color };
                            break;
                        case 2:
                            obj.itemStyle = { 'color': item.device_error_color };
                            break;
                    }

                    res.push(obj);
                });

                return res;
            }

            const effectScatter_utemp_device = function (data) {
                let res = [];

                data.map(function (item) {

                    var obj = {
                        device_guid: item.device_guid,
                        device_full_name: item.device_full_name,
                        status: item.status,
                        symbol: 'image://' + item.device_image_url,
                        value: item.value
                    }

                    res.push(obj);
                });

                return res;
            }

            if (!myChart.getOption()) {
                return;
            }


            var zoom = 0
            if (myChart.getOption().geo && myChart.getOption().geo.length > 0) {
                zoom = myChart.getOption().geo[0].zoom;
            }

            if (zoom <= 8) {

                myChart.setOption({
                    series: [{
                        symbolOffset: [0, 0],
                        data: scatter_symbol_unselect_convertData(currentData)
                    }, {
                        data: []
                    }, {
                        data: []
                    }, {
                        data: scatter_symbol_temp_device(temp_device_on_floor_map)
                    }, {
                        data: []
                    }]
                });
            } else {

                myChart.setOption({
                    series: [{
                        symbolOffset: [10, 10],
                        data: scatter_symbol_unselect_convertData(currentData)
                    }, {
                        data: scatter_icon_unselect_convertData(currentData),
                    }, {
                        data: effectScatter_icon_selected_convertData(currentData),
                    }, {
                        symbolOffset: [10, 10],
                        data: scatter_symbol_temp_device(temp_device_on_floor_map)
                    }, {
                        data: effectScatter_utemp_device(temp_device_on_floor_map),
                    }]
                });
            }
        }
        //#endregion

        //#region 重製平面圖
        function ResetFloorMap() {
            myChart.clear();
            myChart.setOption(option);
            resetData();
        }
        //#endregion

        //#region 變更平面圖模式
        function ChangeFloorMapMode(mode = "") {
            floor_map_mode = mode;
            switch (floor_map_mode) {
                case 'edit':
                    $('#floor-map-mode-text').html("編輯模式");
                    $('#floor-map-edit-mode-btn-wrap').show();
                    $('#device_info_table .device-coordinate-btn').attr("disabled", true);
                    break;
                case 'view':
                    $('#floor-map-mode-text').html("檢視模式");
                    $('#floor-map-edit-mode-btn-wrap').hide();
                    $('#device_info_table .device-coordinate-btn').attr("disabled", false);
                    break;
            }
        }
        //#endregion

        //#region 取消編輯平面圖模式
        function CancelFloorMapEdit() {
            temp_device_on_floor_map = [];

            var index = currentData.findIndex(function (item) { return item.device_guid === selected_temp_device.device_guid });

            currentData[index].selected = false;

            if (selected_temp_device.device_node_guid != undefined && selected_temp_device.device_node_guid != null && selected_temp_device.device_node_guid != "") {
                var node_index = currentData[index].device_nodes.findIndex(function (item) { return item.device_node_guid === selected_temp_device.device_node_guid });

                currentData[index].device_nodes[node_index].selected = false;
            }

            selected_temp_device = {}; //清空

            resetData();
            ChangeFloorMapMode("view");
        }
        //#endregion

        //#region 儲存編輯平面圖模式
        function SaveFloorMapEdit() {
            var new_coordinate = temp_device_on_floor_map[0].value;

            coordinate = new_coordinate[0].toFixed(3).toString() + "," + new_coordinate[1].toFixed(3).toString();

            var index = currentData.findIndex(function (item) { return item.device_guid === selected_temp_device.device_guid });

            var url = "/DeviceManage/SaveDeviceCoordinate";

            var send_data = {
                Device_guid: selected_temp_device.device_guid,
                Device_node_guid: selected_temp_device.device_node_guid,
                Coordinate: coordinate
            }

            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    if (rel.code == "9999") {
                        toast_error(rel.msg);
                    }
                    else {
                        toast_warning(rel.msg);
                    }
                    return;
                }
                else {

                    temp_device_on_floor_map = [];
                    deviceInfoTable.ajax.reload(null, false);
                    ChangeFloorMapMode("view");
                    return;
                }
            }, 'json')
        }
        //#endregion

        //#region 新增設備
        function AddDevice() {

            var selectedBuilding_tag = selected_building_menu.building_tag ? selected_building_menu.building_tag : "";
            var selectedMain_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.main_system_tag : "";
            var selectedSub_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.sub_system ? selected_building_menu.main_system.sub_system.sub_system_tag : "" : "";
            var selectedFloor_tag = selected_floor_tag ? selected_floor_tag : "";
            if (selectedBuilding_tag == '' || selectedMain_system_tag == '' || selectedSub_system_tag == '' || selectedFloor_tag == '') {
                toast_warning("請先選擇系統類別及樓層。");
                return;
            }


            //取得上方選單過濾列表
            var url = "/DeviceManage/GetDeviceImportCheckTempFilter";

            $.post(url, null, function (rel) {
                if (rel.code != "0000") {
                    if (rel.code == "9999") {
                        toast_error(rel.msg);
                    }
                    else {
                        toast_warning(rel.msg);
                    }
                    return;
                }
                else {
                    deviceImportCheckTempFilterList = rel.data;

                    $("#import-temp-building-tag-list").empty();

                    var html = '';

                    deviceImportCheckTempFilterList.forEach(function (building_item, building_tag_index) {
                        html += `<button type="button" class="btn btn-secondary waves-effect waves-themed mr-2 btn-building-tag" onclick="ChangeDeviceImportPanel('${building_item.device_building_tag}')">${building_item.device_building_tag}</button>`
                    });

                    $('#import-temp-building-tag-list').append(html);

                    $('#import-temp-building-tag-list').children().first().trigger('click');

                    $("#device-info-add-modal").modal();

                    return;
                }
            }, 'json');
        }
        //#endregion

        //#region 變更新增設備基本資料modal的過濾條件
        function ChangeDeviceImportPanel(building_tag, system_tag = "", floor_tag = "") {
            if (building_tag == undefined && building_tag == null || building_tag == "") {
                toast_warning("請先選擇棟別");
                return;
            }

            if ($(".btn-building-tag").hasClass("btn-success")) {
                $(".btn-building-tag").removeClass("btn-success").addClass("btn-secondary");
            }

            $(".btn-building-tag").each(function (index, item) {
                if ($(item).text() == building_tag) {
                    $(item).removeClass("btn-secondary").addClass("btn-success");
                }
            });

            $('#import-temp-system-tag-list').empty();
            deviceImportCheckTempFilterList.forEach(function (building_item, building_item_index) {
                if (building_item.device_building_tag == building_tag) {
                    var system_html = '';

                    building_item.device_system_tags.forEach(function (system_item, system_item_index) {
                        if (system_item.device_system_tag == system_tag) {
                            system_html += `<button type="button" class="btn btn-success waves-effect waves-themed mr-2 mb-2" onclick="ChangeDeviceImportPanel('${building_item.device_building_tag}', '${system_item.device_system_tag}')">${system_item.device_system_tag}</button>`
                        }
                        else {
                            system_html += `<button type="button" class="btn btn-secondary waves-effect waves-themed mr-2 mb-2" onclick="ChangeDeviceImportPanel('${building_item.device_building_tag}', '${system_item.device_system_tag}')">${system_item.device_system_tag}</button>`
                        }
                    });

                    $('#import-temp-system-tag-list').append(system_html);

                    if (system_tag == '') {
                        $('#import-temp-system-tag-list').children().first().trigger('click');
                        return;
                    } else {
                        $('#import-temp-floor-tag-list').empty();
                        building_item.device_system_tags.forEach(function (system_item, system_item_index) {
                            if (system_item.device_system_tag == system_tag) {
                                var floor_html = '';

                                system_item.device_floor_tags.forEach(function (floor_item, floor_item_index) {
                                    if (floor_item.device_floor_tag == floor_tag) {
                                        floor_html += `<button type="button" class="btn btn-success waves-effect waves-themed mr-2 mb-2" onclick="ChangeDeviceImportPanel('${building_item.device_building_tag}', '${system_item.device_system_tag}', '${floor_item.device_floor_tag}')">${floor_item.device_floor_tag}</button>`
                                    }
                                    else {
                                        floor_html += `<button type="button" class="btn btn-secondary waves-effect waves-themed mr-2 mb-2" onclick="ChangeDeviceImportPanel('${building_item.device_building_tag}', '${system_item.device_system_tag}', '${floor_item.device_floor_tag}')">${floor_item.device_floor_tag}</button>`
                                    }
                                });

                                $('#import-temp-floor-tag-list').append(floor_html);

                                if (floor_tag == '') {
                                    $('#import-temp-floor-tag-list').children().first().trigger('click');
                                    return;
                                } else {
                                    $('#import-temp-name-tag-list').empty();
                                    system_item.device_floor_tags.forEach(function (floor_item, floor_item_index) {
                                        if (floor_item.device_floor_tag == floor_tag) {
                                            var name_html = '';
                                            floor_item.device_name_tags.forEach(function (name_item, name_item_index) {
                                                name_html += `<button type="button" class="btn btn-secondary waves-effect waves-themed mr-2 mb-2 btn-name-tag"
                                                                onclick="ChangeDeviceImportCheckTempTable(
                                                                    '${building_item.device_building_tag}',
                                                                    '${system_item.device_system_tag}',
                                                                    '${floor_item.device_floor_tag}',
                                                                    '${name_item}')">${name_item}</button>`;
                                            });

                                            $('#import-temp-name-tag-list').append(name_html);
                                        }
                                    });

                                    $('#import-temp-name-tag-list').children().first().trigger('click');
                                }
                            }
                        });
                    }
                }
            });
        }
        //#endregion

        //#region 變更新增設備基本資料modal的列表
        function ChangeDeviceImportCheckTempTable(building_tag = "", system_tag = "", floor_tag = "", name_tag = "") {
            if ($(".btn-name-tag").hasClass("btn-success")) {
                $(".btn-name-tag").removeClass("btn-success").addClass("btn-secondary");
            }

            $(".btn-name-tag").each(function (index, item) {
                if ($(item).text() == name_tag) {
                    $(item).removeClass("btn-secondary").addClass("btn-success");
                }
            });

            selected_building_tag = building_tag;
            selected_system_tag = system_tag;
            selected_floor_tag = floor_tag;
            selected_name_tag = name_tag;

            deviceImportCheckTempTable.ajax.reload(null, false);
        }
        //#endregion

        //#region 設備儲存(透過新增按鈕)
        function SaveDeviceAdd() {

            var selectedBuilding_tag = selected_building_menu.building_tag ? selected_building_menu.building_tag : "";
            var selectedMain_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.main_system_tag : "";
            var selectedSub_system_tag = selected_building_menu.main_system ? selected_building_menu.main_system.sub_system ? selected_building_menu.main_system.sub_system.sub_system_tag : "" : "";
            var selectedFloor_tag = selected_floor_tag ? selected_floor_tag : "";
            if (selectedBuilding_tag == '' || selectedMain_system_tag == '' || selectedSub_system_tag == '' || selectedFloor_tag == '')
            {
                toast_warning("請先選擇系統類別及樓層。");
                return;
            }

            var rows = deviceImportCheckTempTable.rows({ 'search': 'applied' }).nodes();
            //取得被選擇的設備
            var selectedDevices = $("input[name='selectedDevice[]']:checked", rows).map(function () {
                var system_category = $(this).attr('data-system-category');
                var device_disasters = $(this).attr('data-device-disaster');
                return {
                    Device_number: $(this).val(),
                    Device_system_category_layer3: system_category,
                    Device_disasters: device_disasters
                };
            }).get();

            if (selectedDevices.length <= 0) {
                toast_warning("請選擇欲加入設備。");
                return;
            }

            var json_selectedDevices = JSON.stringify(selectedDevices);
            var blob = new Blob([json_selectedDevices],
                { type: "text/plain;charset=utf-8" });

            var url = "/DeviceManage/SaveDeviceInfoAdd";

            @*var send_data = {
                Building_tag: selectedBuilding_tag,
                Main_system_tag: selectedMain_system_tag,
                Sub_system_tag: selectedSub_system_tag,
                Floor_tag: selectedFloor_tag,
                SelectedDevices: selectedDevices
            }

            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

                toast_ok(rel.msg);
                $("#device-info-add-modal").modal('hide');

                deviceInfoTable.ajax.reload();
                deviceKindTable.ajax.reload(null, false);
            }, 'json');*@

            $("#save-device-add-btn").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>').attr("disabled", true);


            var formData = new FormData();
            formData.append("Building_tag", selectedBuilding_tag);
            formData.append("Main_system_tag", selectedMain_system_tag);
            formData.append("Sub_system_tag", selectedSub_system_tag);
            formData.append("Floor_tag", selectedFloor_tag);
            formData.append("SelectedDevicesFile", blob);

            $.ajax({
                type: "POST",
                url: url,
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (rel) {
                    $("#save-device-add-btn").html('確定').attr("disabled", false);
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }

                    toast_ok(rel.msg);
                    $("#device-info-add-modal").modal('hide');

                    deviceInfoTable.ajax.reload();
                    deviceKindTable.ajax.reload(null, false);
                },
                fail: function (jqXHR, textStatus, errorThrown) {
                    $("#save-device-add-btn").html('確定').attr("disabled", false);
                }
            });
        }
        //#endregion

        //#region 設備基本資料表單驗證
        var DeviceInfoValidate = $("#device-info-edit-form").validate({
            rules: {
                device_name_modal: {
                    // required: true,
                    maxlength: 50,
                    filterspace: true
                },
                device_ip_modal: {
                    regex: /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
                },
                device_port_modal: {
                    number: true
                }
            },
            messages: {
                device_ip_modal: {
                    regex: "請輸入正確的設備IP"
                }
            }
        });
        //#endregion



        //#region 設備儲存(透過修改按鈕)
        function SaveDeviceInfoEdit() {
            if ($("#device-info-edit-form").valid()) {

                var select_disasters = $("input[name='selectDisaster[]']:checked").map(function () {
                    return $(this).val();
                }).get();

                var url = "/DeviceManage/SaveDeviceInfoEdit";
                var send_data = {
                    Device_guid: selected_device_guid,
                    Full_name: $("#device_name_modal").val(),
                    Device_coordinate_x: $("#device_coordinate_x_modal").val(),
                    Device_coordinate_y: $("#device_coordinate_y_modal").val(),
                    Device_disasters: select_disasters,
                    Device_ip: $("#device_ip_modal").val(),
                    Device_port: $("#device_port_modal").val(),
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                        }
                        else {
                            toast_warning(rel.msg);
                        }
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        deviceInfoTable.ajax.reload(null, false);
                        $("#device-info-edit-modal").modal('hide');
                        return;
                    }
                }, 'json');
            }
        }
        //#endregion

        //#region 設備子節點表單驗證
        var DeviceNodeValidate = $("#device-node-form").validate({
            rules: {
                device_node_name_modal: {
                    required: true,
                    maxlength: 50,
                    filterspace: true
                },
            }
        });
        //#endregion

        //#region 設備子節點儲存
        function SaveDeviceNode() {
            if ($("#device-node-form").valid()) {

                var url = "/DeviceManage/SaveDeviceNode";
                var send_data = {
                    Device_guid: selected_device_guid,
                    Device_node_guid: selected_device_node_guid,
                    Full_name: $("#device_node_name_modal").val(),
                    Device_node_coordinate_x: $("#device_node_coordinate_x_modal").val(),
                    Device_node_coordinate_y: $("#device_node_coordinate_y_modal").val(),
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        if (rel.code == "9999") {
                            toast_error(rel.msg);
                        }
                        else {
                            toast_warning(rel.msg);
                        }
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        deviceInfoTable.ajax.reload(null, false);

                        @*Object.keys(selected_device_parents_collapses).forEach(key => {
                            var tr = selected_device_parents_collapses[key];
                            var row = deviceInfoTable.row(tr);

                            if (row.child.isShown()) {
                                // This row is already open - close it
                                row.child.hide();
                                tr.removeClass('shown');
                                tr.find("td").first().html(`<i class="fal fa-plus"></i>`);
                            }
                            else {
                                // Open this row
                                console.log(row.data());
                                row.child(DeviceNodeFormat(row.data().device_nodes)).show();
                                tr.addClass('shown');
                                tr.find("td").first().html(`<i class="fal fa-minus"></i>`);
                            }
                        });*@

                        $("#device-node-modal").modal("hide");
                        return;
                    }
                }, 'json');
            }
        }
        //#endregion

        //#region 設備種類表單驗證
        var DeviceKindValidate = $("#device-kind-form").validate({
            rules: {
                device_image_modal: {
                    accept: "image/*"
                },
                device_normal_text_modal: {
                    // required: true,
                    maxlength: 7,
                    filterspace: true
                },
                device_normal_color_modal: {
                    // required: true,
                    maxlength: 7,
                    filterspace: true
                },
                device_close_color_modal: {
                    // required: true,
                    maxlength: 7,
                    filterspace: true
                },
                device_error_color_modal: {
                    // required: true,
                    maxlength: 7,
                    filterspace: true
                },
            }
        });
        //#endregion

        //#region 設備種類儲存
        function SaveDeviceKind() {
            if ($("#device_normal_point_name_modal").val() != ""
                && $("#device_normal_point_name_modal option:selected").text() != "ER"
                && $("#device_close_point_name_modal").val() != ""
                && $("#device_close_point_name_modal option:selected").text() != "ER"
                && $("#device_normal_point_name_modal").val() != $("#device_close_point_name_modal").val()) {
                toast_warning("點位名稱設定需相同");
                return;
            }

            if ($("#device_normal_point_value_modal").val() == $("#device_close_point_value_modal").val()) {
                toast_warning("點位值設定重複,請修改");
                return;
            }

            if ($("#device-kind-form").valid()) {

                $("#save-device-kind-btn").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>').attr("disabled", true);


                var url = "/DeviceManage/SaveDeviceKind";

                var formData = new FormData();

                formData.append("Device_kind_guid", selected_device_kind_guid);
                formData.append("Device_building_tag", selected_device_building_tag);
                formData.append("Device_system_tag", selected_device_system_tag);
                formData.append("Device_floor_tag", selected_device_floor_tag);
                formData.append("Device_name_tag", selected_device_name_tag);

                formData.append("Device_normal_text", $("#device_normal_text_modal").val());
                if ($("#device_normal_point_name_modal").val() != null && $("#device_normal_point_name_modal").val() != "") {
                    formData.append("Device_normal_point_guid", $("#device_normal_point_name_modal").val());

                    if ($("#device_normal_point_col_modal").val() != null && $("#device_normal_point_col_modal").val() != "") {
                        formData.append("Device_normal_point_col", $("#device_normal_point_col_modal").val());
                    }
                    if ($("#device_normal_point_value_modal").val() != null && $("#device_normal_point_value_modal").val() !="") {
                        formData.append("Device_normal_point_value", $("#device_normal_point_value_modal").val());
                    }
                }

                formData.append("Device_normal_color", $("#device_normal_color_modal").val());
                formData.append("Device_normal_flashing", $("#device_normal_flashing_modal:checked").val());

                formData.append("Device_close_text", $("#device_close_text_modal").val());
                if ($("#device_close_point_name_modal").val() != null && $("#device_close_point_name_modal").val() != "") {
                    formData.append("Device_close_point_guid", $("#device_close_point_name_modal").val());
                    if ($("#device_close_point_col_modal").val() != null && $("#device_close_point_col_modal").val() != "") {
                        formData.append("Device_close_point_col", $("#device_close_point_col_modal").val());
                    }
                    if ($("#device_close_point_value_modal").val() != null && $("#device_close_point_value_modal").val() != "") {
                        formData.append("Device_close_point_value", $("#device_close_point_value_modal").val());
                    }
                }
                formData.append("Device_close_color", $("#device_close_color_modal").val());
                formData.append("Device_close_flashing", $("#device_close_flashing_modal:checked").val());

                formData.append("Device_error_text", $("#device_error_text_modal").val());
                if ($("#device_error_point_name_modal").val() != null && $("#device_error_point_name_modal").val() != "") {
                    formData.append("Device_error_point_guid", $("#device_error_point_name_modal").val());
                    if ($("#device_error_point_col_modal").val() != null && $("#device_error_point_col_modal").val() != "") {
                        formData.append("Device_error_point_col", $("#device_error_point_col_modal").val());
                    }
                    if ($("#device_error_point_value_modal").val() != null && $("#device_error_point_value_modal").val() != "") {
                        formData.append("Device_error_point_value", $("#device_error_point_value_modal").val());
                    }
                }
                formData.append("Device_error_color", $("#device_error_color_modal").val());
                formData.append("Device_error_flashing", $("#device_error_flashing_modal:checked").val());
                formData.append("Device_error_independent", $("#device_error_independent_modal:checked").val());

                @*formData.append("Device_close_color", $("#device_close_color_modal").val());
                formData.append("Device_error_color", $("#device_error_color_modal").val());
                formData.append("Device_flashing", $("#device_normal_flashing_modal:checked").val());*@

                imgs = $('#device_image_modal')[0].files
                if (imgs.length > 0) {

                    var file_names = imgs[0].name.split(".")

                    formData.append("Device_image_file", imgs[0])
                    formData.append("InitDeviceName", imgs[0].name);
                }

                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (rel) {
                        $("#save-device-kind-btn").html('確定').attr("disabled", false);
                        if (rel.code != "0000") {
                            if (rel.code == "9999") {
                                toast_error(rel.msg);
                            }
                            else {
                                toast_warning(rel.msg);
                            }
                            return;
                        }
                        else {
                            toast_ok(rel.msg);
                            deviceKindTable.ajax.reload(null, false);
                            $("#device-kind-modal").modal('hide');
                            return;
                        }
                    },
                    fail: function (jqXHR, textStatus, errorThrown) {
                        $("#save-device-kind-btn").html('確定').attr("disabled", false);
                    }
                });
            }
        }
        //#endregion

        //#region 設備Master表單驗證
        var DeviceMasterValidate = $("#device-master-form").validate({
            rules: {
                device_master_icon_modal: {
                    accept: "image/*"
                },
                device_master_full_name_modal: {
                    // required: true,
                    filterspace: true
                }
            }
        });
        //#endregion

        //#region 設備Master儲存
        function SaveDeviceMaster() {

            if ($("#device-master-form").valid()) {

                var url = "/DeviceManage/SaveDeviceMaster";

                var formData = new FormData();

                formData.append("Device_master_guid", selected_device_master_guid);
                formData.append("Device_building_tag", selected_device_building_tag);
                formData.append("Device_name_tag", selected_device_name_tag);
                formData.append("Device_master_full_name", $("#device_master_full_name_modal").val());


                imgs = $('#device_master_icon_modal')[0].files
                if (imgs.length > 0) {
                    formData.append("Device_master_icon_file", imgs[0])
                }

                $("#save-device-master-btn").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>').attr("disabled", true);

                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (rel) {
                        $("#save-device-master-btn").html('確定').attr("disabled", false);
                        if (rel.code != "0000") {
                            if (rel.code == "9999") {
                                toast_error(rel.msg);
                            }
                            else {
                                toast_warning(rel.msg);
                            }
                            return;
                        }
                        else {
                            toast_ok(rel.msg);
                            deviceMasterTable.ajax.reload(null, false);
                            $("#device-master-edit-modal").modal('hide');
                            return;
                        }
                    },
                    fail: function (jqXHR, textStatus, errorThrown) {
                        $("#save-device-master-btn").html('確定').attr("disabled", false);
                    }
                });
            }
        }
        //#endregion

    </script>
}