@{
    ViewData["MainNum"] = "8";
    ViewData["SubNum"] = "1";
    ViewData["Title"] = "電站管理";
}
@using SolarPower.Models.Role
@model RoleLayerEnum

<ol class="breadcrumb page-breadcrumb">
    <li class="breadcrumb-item"><a href="javascript:void(0);">總覽</a></li>
    <li class="breadcrumb-item">@ViewData["Title"]</li>
    <li class="breadcrumb-item city-name">新竹市</li>
    <li class="breadcrumb-item power-station-name active">新竹巨城站</li>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>

<!-- Your main content goes below here: -->
<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="subheader">
                        <h1 class="subheader-title">
                            <span class="icon-stack fa-1x">
                                <i class="base-7 icon-stack-3x color-info-500"></i>
                                <i class="base-7 icon-stack-2x color-info-700"></i>
                                <i class="ni ni-graph icon-stack-1x text-white"></i>
                            </span>
                            <span id="power-station-title">
                                新增電站
                            </span>
                        </h1>
                    </div>
                    <ul class="nav nav-tabs mb-5" role="tablist" id="tablist">
                        <li class="nav-item">
                            <a class="nav-link fs-lg px-4 active" data-toggle="tab" href="#tab-station-info" role="tab">
                                <i class="fal fa-server text-success"></i> <span class="hidden-sm-down ml-1">電站資料</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link fs-lg px-4" data-toggle="tab" href="#tab-device-setting" role="tab">
                                <i class="fal fa-list-alt text-success"></i> <span class="hidden-sm-down ml-1">裝置列表</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link fs-lg px-4" data-toggle="tab" href="#tab-operation-firm" role="tab">
                                <i class="fal fa-hands-helping text-success"></i> <span class="hidden-sm-down ml-1">維運廠商</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link fs-lg px-4" data-toggle="tab" href="#tab-upload-image" role="tab">
                                <i class="fal fa-upload text-success"></i> <span class="hidden-sm-down ml-1">資料上傳</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link fs-lg px-4" data-toggle="tab" href="#tab-exception" role="tab">
                                <i class="fal fa-sensor-alert text-success"></i> <span class="hidden-sm-down ml-1">異常設定</span>
                            </a>
                        </li>

                    </ul>
                    <div class="tab-content p-3">
                        <div class="tab-pane fade show active" id="tab-station-info" role="tabpanel" aria-labelledby="tab-station-info">
                            @Html.Partial("_StationInfo")
                        </div>

                        <div class="tab-pane fade" id="tab-device-setting" role="tabpanel" aria-labelledby="tab-device-setting">
                            @Html.Partial("_DeviceSetting")
                        </div>

                        <div class="tab-pane fade" id="tab-operation-firm" role="tabpanel" aria-labelledby="tab-operation-firm">
                            @Html.Partial("_Operation")
                        </div>

                        <div class="tab-pane fade" id="tab-upload-image" role="tabpanel" aria-labelledby="tab-upload-image">
                            @Html.Partial("_UploadImage")
                        </div>

                        <div class="tab-pane fade" id="tab-exception" role="tabpanel" aria-labelledby="tab-exception">
                            @Html.Partial("_Exception")
                        </div>


                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="page-content-overlay" data-action="toggle" data-class="mobile-nav-on"></div>

@section Scripts{
    <script>
        var stationId;
        var powerStationData;
        var selectedLandBuildingId;
        var isLandBuildingLock = false;
        var selected_id = 0;
        var countPowerStationImage = 0; var countPowerStationSingleLine = 0;
        var upper = 0;
        var stationDB = "";
        var station_infocreate = false;
        $(function () {
            $('#power_station_operation_personnel-error').hide();
            $('#coordinate_text-error').hide();
            var url = new URL(location.href);
            stationId = url.searchParams.get('stationId');

            //#region 預先載入公司下拉式選單select_option
            var url_company_select_option = "/PowerStation/GetCompanySelectOptionList";
            $.get(url_company_select_option, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

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

                $.each(rel.data, function (index, val) {
                    $("#select_power_station_company").append($("<option />").val(val.value).text(val.text));
                });

                //預設查詢自己的公司
                if (powerStationData == undefined || powerStationData == null) {
                    $("#select_power_station_company").val(@ViewBag.myUser.CompanyId).trigger('change');
                }
                else {
                    $("#select_power_station_company").val(powerStationData.companyId).trigger('change');
                }
            });
            //#endregion

            //#region 電站資料 view 控制
            if (stationId == 'new') {
                //#region 電站基本資料
                $("#address_detail_text").hide();
                $("#select_solar_tpye").attr('disabled', false);

                $("#power_station_code_text").hide();
                $("#power_station_name_text").hide();
                $("#check_escrow").attr('disabled', false);
                $("#escrow_name_text").hide();

                $("#generating_capacity_text").hide();
                $("#estimate_efficacy_text").hide();
                $("#estimate_kwh_text").hide();
                $("#estimated_recovery_time_text").hide();

                $("#coordinate_text").hide();
                $("#line_token_text").hide();

                $("#created_by_title").hide();
                $("#created_by_text").hide();
                $("#created_at_title").hide();
                $("#created_at_text").hide();


                //逆變器
                $("#inverter_brand_text").hide();
                $("#inverter_product_model_text").hide();
                $("#inverter_amount_text").hide();

                //光電板
                $("#photovoltaic_panel_brand_text").hide();
                $("#photovoltaic_panel_specification_text").hide();
                $("#photovoltaic_panel_amount_text").hide();
                $("#photovoltaic_panel_product_model_text").hide();
                //#endregion

                $("#edit-station-info-btn").hide();
                $("#canecl-station-info-btn").hide();

                @if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformUser)
                {
                    <text>
                    $("#select_power_station_company_title").show();
                    $("#select_power_station_company").show();
                    $("#select_power_station_company").attr('disabled', false);
                    </text>
                }
                else
                {
                    <text>
                    $("#select_power_station_company_title").hide();
                    $("#select_power_station_company").hide();
                    $("#select_power_station_company").attr('disabled', true);
                    </text>
                }

                $(".city-name").hide();
                $(".power-station-name").html("新增電站");


                $("#BoEPart").hide();
                $("#land_buildingPart").hide();

                $("#tablist").hide();
                $("#tablist").find(".nav-item > a").first().click();

            } else {
                var url = "/PowerStation/GetOnePowerStation"

                var send_data = {
                    id: stationId
                }

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

                    powerStationData = rel.data;

                    $(".city-name").html(powerStationData.cityName);
                    $(".power-station-name").html(powerStationData.name);

                    //#region 電站基本資料
                    ChangeMode("station_info", "view");
                    SetStationInfo();
                    //#endregion

                    //#region 能源局與台電資料
                    ChangeMode("BOE_TPC", "view");
                    SetBoETPCInfo();
                    //#endregion

                    //#region 土地與房屋資料
                    ChangeMode("land_building_info", "view");
                    SetLandBuildingInfo();
                    //#endregion

                }, 'json');

                //#region 控制器列表 DataTable
                DeviceControllerTable = $("#Controller_table").DataTable({
                    "pageLength": 5,
                    "paging": true,
                    "lengthChange": false,
                    "searching": false,
                    "ordering": true,
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "columns": [{
                        "data": "controllerId"
                    }, {
                        "data": "createdAt"
                    }, {
                        "data": "createdName"
                    }, {
                        "data": "function"
                    }],
                    "language": {
                        "emptyTable": "查無資料",
                        "processing": "處理中...",
                        "loadingRecords": "載入中...",
                        "lengthMenu": "顯示 _MENU_ 項結果",
                        "zeroRecords": "沒有符合的結果",
                        "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                        "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                        "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                        "infoPostFix": "",
                        "search": "搜尋:",
                        "paginate": {
                            "first": "第一頁",
                            "previous": "上一頁",
                            "next": "下一頁",
                            "last": "最後一頁"
                        }
                    },
                    'createdRow': function (row, data, dataIndex) {
                        $(row).attr('data-id', data.id);
                    },
                    "ajax": {
                        "url": "/PowerStation/DeviceControllerControllerTable",
                        "type": "POST",
                        "data": function (d) {
                            d.stationId = stationId;
                        },
                        "dataSrc": function (rel) {
                            if (rel.data.code == "9999") {
                                toast_error(rel.data.msg);
                                return;
                            }

                            data = rel.data.data;

                            if (data == null || data.length == 0) {
                                this.data = [];
                            }
                            $("#Inverter_ControllerId_modal").empty();
                            $("#Device_Controller_modal").empty();

                            $.each(data, function (index, val) {
                                $("#Inverter_ControllerId_modal").append($("<option />").val(val.id).text(val.controllerId));
                            });
                            $.each(data, function (index, val) {
                                $("#Device_Controller_modal").append($("<option />").val(val.id).text(val.controllerId));
                            });

                            return data;
                        }
                    },
                    "error": function (xhr, error, thrown) {
                        console.log(xhr);
                    }
                });
                //#endregion

                //#region 逆變器列表 DataTable
                InverterTable = $("#Inverter_table").DataTable({
                    "pageLength": 5,
                    "paging": true,
                    "lengthChange": false,
                    "searching": false,
                    "ordering": true,
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "columns": [{
                            "data": "controllerName"
                        }, {
                            "data": "inverterId"
                        }, {
                            "data": "inverterName"
                        }, {
                            "data": "enabledName"
                        }, {
                            "data": "statusName"
                        }, {
                            "data": "installDate"
                        }, {
                            "data": "brand"
                        }, {
                            "data": "brandNum"
                        }, {
                            "data": "model"
                        }, {
                            "data": "capacity"
                        }, {
                            "data": "pyrheliometerName"
                        }, {
                            "data": "warrantyDate"
                        }, {
                            "data": "function"
                        }],
                    "language": {
                        "emptyTable": "查無資料",
                        "processing": "處理中...",
                        "loadingRecords": "載入中...",
                        "lengthMenu": "顯示 _MENU_ 項結果",
                        "zeroRecords": "沒有符合的結果",
                        "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                        "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                        "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                        "infoPostFix": "",
                        "search": "搜尋:",
                        "paginate": {
                            "first": "第一頁",
                            "previous": "上一頁",
                            "next": "下一頁",
                            "last": "最後一頁"
                        }
                    },
                    'createdRow': function (row, data, dataIndex) {
                        $(row).attr('data-id', data.id);
                    },
                    "ajax": {
                        "url": "/PowerStation/InverterTable",
                        "type": "POST",
                        "data": function (d) {
                            d.stationId = stationId;
                        },
                        "dataSrc": function (rel) {
                            if (rel.data.code == "9999") {
                                toast_error(rel.data.msg);
                                return;
                            }
                            data = rel.data.data;
                            $.each(data, function (index, val) {
                                if (val.warrantyDate == "0001-01-01") {
                                    val.warrantyDate = "";
                                }

                            });


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

                            return data;
                        }
                    },
                    "error": function (xhr, error, thrown) {
                        console.log(xhr);
                    }
                });
                //#endregion

                //#region 運維列表 DataTable
                OperationTable = $("#Operation_table").DataTable({
                    "paging": true,
                    "lengthChange": false,
                    "searching": false,
                    "ordering": true,
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "order": [[7, "desc"]],
                    "columns": [{
                        "data": "typeName"
                    }, {
                        "data": "name"
                    }, {
                        "data": "contactPerson"
                    }, {
                        "data": "phone"
                    }, {
                        "data": "email"
                    }, {
                        "data": "createdAt"
                    }, {
                        "data": "createdName"
                    }, {
                        "data": "function"
                    }],
                    "language": {
                        "emptyTable": "查無資料",
                        "processing": "處理中...",
                        "loadingRecords": "載入中...",
                        "lengthMenu": "顯示 _MENU_ 項結果",
                        "zeroRecords": "沒有符合的結果",
                        "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                        "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                        "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                        "infoPostFix": "",
                        "search": "搜尋:",
                        "paginate": {
                            "first": "第一頁",
                            "previous": "上一頁",
                            "next": "下一頁",
                            "last": "最後一頁"
                        },
                        "aria": {
                            "sortAscending": ": 升冪排列",
                            "sortDescending": ": 降冪排列"
                        }
                    },
                    'createdRow': function (row, data, dataIndex) {
                        $(row).attr('data-id', data.id);
                    },
                    "ajax": {
                        "url": "/PowerStation/OperationTable",
                        "type": "POST",
                        "data": function (d) {
                            d.stationId = stationId;
                        },
                        "dataSrc": function (rel) {
                            if (rel.data.code == "9999") {
                                toast_error(rel.data.msg);
                                return;
                            }

                            data = rel.data.data;

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

                            return data;
                        }
                    },
                    "error": function (xhr, error, thrown) {
                        console.log(xhr);
                    }
                });
                //#endregion

                //#region 裝置列表 DataTable
                DeviceTable = $("#Device_table").DataTable({
                    "paging": true,
                    "lengthChange": false,
                    "searching": false,
                    "ordering": true,
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "order": [[13, "desc"]],
                    "columns": [{
                        "data": "powerStationName"
                    }, {
                        "data": "controllerName"
                    }, {
                        "data": "uid"
                    }, {
                        "data": "name"
                    },{
                        "data": "enabledName"
                    }, {
                        "data": "statusName"
                    },{
                        "data": "typeName"
                    },{
                        "data": "brand"
                    }, {
                        "data": "brandNum"
                    }, {
                        "data": "productModel"
                    }, {
                        "data": "installDate"
                    }, {
                        "data": "warrantyDate"
                    }, {
                        "data": "dbName"
                    }, {
                        "data": "tableName"
                    }, {
                        "data": "colName"
                    }, {
                        "data": "function"
                    }],
                    "columnDefs": [{
                        'targets': 0,
                        'visible': false
                    }],
                    "language": {
                        "emptyTable": "查無資料",
                        "processing": "處理中...",
                        "loadingRecords": "載入中...",
                        "lengthMenu": "顯示 _MENU_ 項結果",
                        "zeroRecords": "沒有符合的結果",
                        "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                        "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                        "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                        "infoPostFix": "",
                        "search": "搜尋:",
                        "paginate": {
                            "first": "第一頁",
                            "previous": "上一頁",
                            "next": "下一頁",
                            "last": "最後一頁"
                        },
                        "aria": {
                            "sortAscending": ": 升冪排列",
                            "sortDescending": ": 降冪排列"
                        }
                    },
                    'createdRow': function (row, data, dataIndex) {
                        $(row).attr('data-id', data.id);
                    },
                    "ajax": {
                        "url": "/PowerStation/DeviceTable",
                        "type": "POST",
                        "data": function (d) {
                            d.stationId = stationId;
                        },
                        "dataSrc": function (rel) {
                            if (rel.data.code == "9999") {
                                toast_error(rel.data.msg);
                                return;
                            }

                            data = rel.data.data;
                            $.each(data, function (index, val) {
                                if (val.warrantyDate == "0001-01-01") {
                                    val.warrantyDate = "";
                                }

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

                            return data;
                        }
                    },
                    "error": function (xhr, error, thrown) {
                        console.log(xhr);
                    }
                });
                //#endregion

                //#region 共享裝置列表 DataTable
                ShareDeviceTable = $("#ShareDevice_table").DataTable({
                    "paging": true,
                    "lengthChange": false,
                    "searching": false,
                    "ordering": true,
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "order": [[13, "desc"]],
                    "columns": [{
                        "data": "powerStationName"
                    }, {
                        "data": "controllerName"
                    }, {
                        "data": "uid"
                    }, {
                        "data": "name"
                    },{
                        "data": "enabledName"
                    }, {
                        "data": "statusName"
                    },{
                        "data": "typeName"
                    },{
                        "data": "brand"
                    }, {
                        "data": "brandNum"
                    }, {
                        "data": "productModel"
                    }, {
                        "data": "installDate"
                    }, {
                        "data": "warrantyDate"
                    }, {
                        "data": "dbName"
                    }, {
                        "data": "tableName"
                    }, {
                        "data": "colName"
                    }, {
                        "data": "function"
                    }],
                    "columnDefs": [{
                        'targets': 0,
                        'visible': false
                    }],
                    "language": {
                        "emptyTable": "查無資料",
                        "processing": "處理中...",
                        "loadingRecords": "載入中...",
                        "lengthMenu": "顯示 _MENU_ 項結果",
                        "zeroRecords": "沒有符合的結果",
                        "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                        "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                        "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                        "infoPostFix": "",
                        "search": "搜尋:",
                        "paginate": {
                            "first": "第一頁",
                            "previous": "上一頁",
                            "next": "下一頁",
                            "last": "最後一頁"
                        },
                        "aria": {
                            "sortAscending": ": 升冪排列",
                            "sortDescending": ": 降冪排列"
                        }
                    },
                    'createdRow': function (row, data, dataIndex) {
                        $(row).attr('data-id', data.id);
                    },
                    "ajax": {
                        "url": "/PowerStation/ShareDeviceTable",
                        "type": "POST",
                        "data": function (d) {
                            d.stationId = stationId;
                        },
                        "dataSrc": function (rel) {
                            if (rel.data.code == "9999") {
                                toast_error(rel.data.msg);
                                return;
                            }

                            data = rel.data.data;
                            $.each(data, function (index, val) {
                                if (val.warrantyDate == "0001-01-01") {
                                    val.warrantyDate = "";
                                }
                            });
                            if (data == null || data.length == 0) {
                                this.data = [];
                            }

                            return data;
                        }
                    },
                    "error": function (xhr, error, thrown) {
                        console.log(xhr);
                    }
                });
                //#endregion

                //#region 異常設定列表 DataTable
                ExceptionTable = $("#Exception_table").DataTable({
                    "paging": true,
                    "lengthChange": false,
                    "searching": false,
                    "ordering": true,
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "order": [[7, "desc"]],
                    "columns": [{
                        "data": "powerStationCode"
                    }, {
                        "data": "powerStationName"
                    }, {
                        "data": "typeName"
                    }, {
                        "data": "lowerLimit"
                    }, {
                        "data": "upperLimit"
                    }, {
                        "data": "alarmName"
                    }, {
                        "data": "createdAt"
                    }, {
                        "data": "function"
                    }],
                    "language": {
                        "emptyTable": "查無資料",
                        "processing": "處理中...",
                        "loadingRecords": "載入中...",
                        "lengthMenu": "顯示 _MENU_ 項結果",
                        "zeroRecords": "沒有符合的結果",
                        "info": "顯示第 _START_ 至 _END_ 項結果，共 _TOTAL_ 項",
                        "infoEmpty": "顯示第 0 至 0 項結果，共 0 項",
                        "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                        "infoPostFix": "",
                        "search": "搜尋:",
                        "paginate": {
                            "first": "第一頁",
                            "previous": "上一頁",
                            "next": "下一頁",
                            "last": "最後一頁"
                        },
                        "aria": {
                            "sortAscending": ": 升冪排列",
                            "sortDescending": ": 降冪排列"
                        }
                    },
                    'createdRow': function (row, data, dataIndex) {
                        $(row).attr('data-id', data.id);
                        $(row).attr('data-typename', data.typeName);
                    },
                    "ajax": {
                        "url": "/PowerStation/ExceptionTable",
                        "type": "POST",
                        "data": function (d) {
                            d.stationId = stationId;
                        },
                        "dataSrc": function (rel) {
                            if (rel.data.code == "9999") {
                                toast_error(rel.data.msg);
                                return;
                            }

                            data = rel.data.data;

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

                            return data;
                        }
                    },
                    "error": function (xhr, error, thrown) {
                        console.log(xhr);
                    }

                });
            //#endregion

                //#region 載入上傳資料 - 電站圖片
                var url_image = "/PowerStation/GetAllPowerStationImage";
                var send_data = {
                    powerStationId: stationId
                };

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

                    var powerStationImages = rel.data;

                    countPowerStationImage = powerStationImages.length;

                    powerStationSingleLineCard = $("#power-station-image-card > .row");
                    powerStationSingleLineCard.empty();
                    rel.data.forEach(function (value, index) {
                        CreatePowerStationImageBox(powerStationSingleLineCard, value);
                    });

                }, 'json');
                //#endregion

                //#region 載入上傳資料 - 單線圖
                var url_image = "/PowerStation/GetAllPowerStationSingleLine";
                var send_data = {
                    powerStationId: stationId
                };

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

                    var powerStationSingleLines = rel.data;

                    countPowerStationSingleLine = powerStationSingleLines.length;

                    powerStationSingleLineCard = $("#power-station-single-line-card > .row");
                    powerStationSingleLineCard.empty();
                    rel.data.forEach(function (value, index) {
                        var split = value.image.split(".");
                        if (split[split.length - 1].toLowerCase() == "pdf") {
                            CreatePowerStationSingleLineBoxPDF(powerStationSingleLineCard, value);
                        } else {
                            CreatePowerStationSingleLineBox(powerStationSingleLineCard, value);
                        }
                    });



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

            //#region 預先載入運維人員下拉式選單select_option
            var url_user_select_option = "/PowerStation/GetUserSelectOptionList";
            var send_data = {
                powerStationId: stationId
            }
            $.get(url_user_select_option, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

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

                $.each(rel.data, function (index, val) {
                    if (val.canBeSelected == 1) {
                        $("#power_station_operation_personnel").append($("<option />").val(val.value).text(val.text).attr({ "disabled": false, "data-canBeSelected": val.canBeSelected }));
                    }
                    else {
                        $("#power_station_operation_personnel").append($("<option />").val(val.value).text(val.text).attr({ "disabled": true, "data-canBeSelected": val.canBeSelected }));
                    }
                });

                if (powerStationData) {
                    $("#power_station_operation_personnel").val(powerStationData.operationPersonnelIds);
                }
            });

            $('.js-example-basic-multiple').select2();
            //#endregion

            //#region 預先載入其餘電站下拉式選單select_option
            var url_powerstation_option = "/PowerStation/GetPowerstationOption";
            var send_data = {
                stationId: stationId
            }
            if (stationId != "new") {
                $.get(url_powerstation_option, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }

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

                    $.each(rel.data, function (index, val) {
                        $("#ShareDevice_PowerStationId_modal").append($("<option />").val(val.value).text(val.text +"/"+ val.name));
                    });
                    if (rel.data.length > 0) {
                        DeviceUIDList($("#ShareDevice_PowerStationId_modal").val());
                        $("#ShareDevice_PowerStationId_modal").attr('disabled', false);
                        $("#ShareDevice-modal").find('.btn-primary').attr('disabled', false);
                    }
                    else
                    {
                        $("#ShareDevice_PowerStationId_modal").append($("<option />").val("").text("無其餘電站"));
                        $("#ShareDevice_PowerStationId_modal").attr('disabled', true);
                        $("#ShareDevice-modal").find('.btn-primary').attr('disabled', true);
                    }
                });
            }

            //#endregion

            $('#ShareDevice_PowerStationId_modal').change(function () {

                DeviceUIDList($("#ShareDevice_PowerStationId_modal").val());
            });

            //#region 預先載入縣市下拉式選單select_option
            var url_city_select_option = "/PowerStation/GetCitySelectOptionList";
            $.get(url_city_select_option, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

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

                $.each(rel.data, function (index, val) {
                    $("#select_city").append($("<option />").val(val.value).text(val.text));
                });

            if (powerStationData == undefined || powerStationData == null) {
                    //預設查詢第一個
                    $("#select_city").val($("#select_city option:first").val()).trigger("change");
                }
                else {
                    $("#select_city").val(powerStationData.cityId).trigger("change");
                }
            });
            //#endregion

            //#region 縣市選擇後取得地區下拉式選單select_option
            $("#select_city").change(function () {
                var url_area_select_option = "/PowerStation/GetAreaSelectOptionList";

                var send_data = {
                    cityId: $(this).val()
                }

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

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

                    $.each(rel.data, function (index, val) {
                        $("#select_area").append($("<option />").val(val.value).text(val.text));
                    });

                    if (powerStationData == undefined || powerStationData == null) {
                        //預設查詢第一個
                        $("#select_area").val($("#select_area option:first").val());
                    }
                    else {
                        $("#select_area").val(powerStationData.areaId);
                    }
                });
            });
            //#endregion

            //#region 預先載入設備類型下拉式選單select_option
            var url_DeviceType = "/PowerStation/GetDeviceTypeSelectOptionList";
            $.get(url_DeviceType, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $("Device_Type_modal").empty();

                $.each(rel.data, function (index, val) {
                    $("#Device_Type_modal").append($("<option />").val(val.value).text(val.text));
                });
            });
            //#endregion


        });

        //#region 代管切換
        $("#check_escrow").click(function () {
            if ($(this).prop("checked")) {
                $('#check_escrow_label').html("Yes");
                $("#escrow_name").attr('disabled', false)
            } else {
                $('#check_escrow_label').html("No");
                $("#escrow_name").attr('disabled', true)
            }
        });
        //#endregion

        //#region 預先載入裝置下拉式選單select_option
        function DeviceUIDList(powerstationid)
        {
            var url_powerstation_option = "/PowerStation/GetDeviceUIDList";
            var send_data = {
                stationId: powerstationid
            }
            $.get(url_powerstation_option, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

                $("#ShareDevice_UID_modal").empty();
                if (rel.data.length == 0) {
                    $("#ShareDevice_UID_modal").append($("<option />").val('0').text("無設備"));
                }
                else {
                    $.each(rel.data, function (index, val) {
                        $("#ShareDevice_UID_modal").append($("<option />").val(val.value).text(val.text + "/" + val.name));
                    });



                }

            });
        }
        //#endregion

        //#region 預先載入日照計下拉式選單select_option
        function PyrheliometerList(powerstationid) {
            var url_powerstation_option = "/PowerStation/GetPyrheliometerList";
            var send_data = {
                stationId: powerstationid
            }
            $.get(url_powerstation_option, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

                $("#Inverter_Pyrheliometer_modal").empty();
                if (rel.data.length == 0) {
                    $("#Inverter_Pyrheliometer_modal").append($("<option />").val('0').text("無設備"));
                }
                else {
                    $("#Inverter_Pyrheliometer_modal").append($("<option />").val('0').text("無設備"));
                    $.each(rel.data, function (index, val) {
                        $("#Inverter_Pyrheliometer_modal").append($("<option />").val(val.value).text(val.text));
                    });

                }

            });
        }
        //#endregion

        //#region 儲存電站基本資料資訊
        function SaveStationInfo() {
            var a = $('#coordinate').val().split(',');

            if ($("#station-created-form").valid() && $('#power_station_operation_personnel').val().length != 0 && a.length == 2) {
                station_infocreate = false;

                $(".select2-selection__choice").each(function () {
                    $(this).children(".select2-selection__choice__remove").show();
                })

                $("#power_station_operation_personnel > option").each(function () {
                    $(this).attr("disabled", false);
                });

                $("#power_station_operation_personnel").select2();


                var ps_company_text = $("#select_power_station_company").find(':selected').text();

                @if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformUser)
                {
                    <text>

                if (stationId == 'new') {
                    Swal.fire(
                        {
                            title: "",
                            text: "你確定是否要將該電站加入至【" + ps_company_text + "】?",
                            type: "question",
                            icon: 'question',
                            showCancelButton: true,
                            confirmButtonText: "是",
                            cancelButtonText: "否"
                        }).then(function (result) {
                            if (result.value) {
                                PostPowerStationData();
                            }
                        });
                } else {
                    PostPowerStationData();
                }
                    </text>
                }
                else
                {
                    <text>
                PostPowerStationData();
                    </text>
                }
            }
            else {
                if ($('#power_station_operation_personnel').val().length == 0) {
                    $('#power_station_operation_personnel-error').show();
                }
            }
        }
        //#endregion

        function PostPowerStationData() {
            var url = "/PowerStation/SavePowerStationInfo";

            var send_data = {
                Id: stationId,
                CityId: $("#select_city").val(),
                AreaId: $("#select_area").val(),
                Address: $("#address_detail").val(),
                Name: $("#power_station_name").val(),
                IsEscrow: $('#check_escrow').is(':checked') ? 1 : 0,
                EstimatedRecoveryTime: $("#estimated_recovery_time").val(),
                GeneratingCapacity: $("#generating_capacity").val(),
                EscrowName: $('#check_escrow').is(':checked') ? $("#escrow_name").val() : "",
                PowerRate: $("#power_rate").val(),
                Coordinate: $("#coordinate").val(),
                OperationPersonnelIds: $("#power_station_operation_personnel").val(),
                InverterBrand: $("#inverter_brand").val(),
                InverterProductModel: $("#inverter_product_model").val(),
                InverterAmount: $("#inverter_amount").val(),
                PhotovoltaicPanelBrand: $("#photovoltaic_panel_brand").val(),
                PhotovoltaicPanelSpecification: $("#photovoltaic_panel_specification").val(),
                PhotovoltaicPanelAmount: $("#photovoltaic_panel_amount").val(),
                PhotovoltaicPanelProductModel: $("#photovoltaic_panel_product_model").val(),
                SolarType: $("#select_solar_tpye").val(),
                line_token: $("#line_token").val(),
                Estimate_kwh: $("#estimate_kwh").val(),
                EstimateEfficacy: $("#estimate_efficacy").val(),
                CompanyId: $("#select_power_station_company").val(),
            }

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

                toast_ok(rel.msg);

                if (stationId == "new") {
                    window.location = "/PowerStation/Edit?stationId=" + rel.data.id
                } else {
                    //回填資料
                    powerStationData = rel.data;
                    SetStationInfo();
                    ChangeMode("station_info", "view");
                }
            }, 'json');
        }

        //#region 儲存能源局台電資料資訊
        function SaveBoETPCInfo() {
            var url = "/PowerStation/SaveBoETPCInfo";

            var formData = new FormData();
            var BoEFile = $('#BoE_file')[0].files;

            formData.append("Id", stationId);
            if (BoEFile.length > 0) {
                formData.append("BoEFile", BoEFile[0]);
            }
            formData.append("BoEDiscountRate", $("#BoE_discount_rate").val());
            formData.append("BoEDeviceRegisterNumber", $("#BoE_device_register_number").val());
            formData.append("BoERegisterPostAt", $("#BoE_register_post_at").val());
            @*formData.append("BoERentRatio", $("#BoE_rent_ratio").val());*@
            formData.append("TPCContractNumber", $("#TPC_contract_number").val());
            formData.append("TPCContractAt", $("#TPC_contract_at").val());
            formData.append("TPCSellDeadline", $("#TPC_sell_deadline").val());
            formData.append("ElectricityMeterAt", $("#electricity_meter_at").val());
            formData.append("PowerRate", $("#power_rate").val());
            @*formData.append("TPCMeterReading", $("#TPC_meter_reading").val());*@
            @*formData.append("TPCPurchaseElectricityAt", $("#TPC_purchase_electricity_at").val());*@
            formData.append("TPCSellElectricityAt", $("#TPC_sell_electricity_at").val());
            formData.append("TPCInvoiceBuyer", $("#TPC_invoice_buyer").val());
            formData.append("GUINumber", $("#GUI_number").val());
            formData.append("TPCInvoiceAddress", $("#TPC_invoice_address").val());
            formData.append("TPCMeterNumber", $("#TPC_meter_number").val());

            $.ajax({
                type: "POST",
                url: url,
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }

                    toast_ok(rel.msg);

                    powerStationData = rel.data;

                    //回填資料
                    SetBoETPCInfo();
                    ChangeMode("BOE_TPC", "view");
                }
            });
        }
        //#endregion

        //#region 儲存土地房屋資訊
        function SaveLandBuildingInfo() {
            var url = "/PowerStation/SaveLandBuildingInfo";

            var send_data = {
                Id: selectedLandBuildingId,
                PowerStationId: stationId,
                Address: $("#land_building_address_" + selectedLandBuildingId).val(),
                LeaseNotarizationAt: $("#lease_notarization_at_" + selectedLandBuildingId).val(),
                Landowner: $("#land_building_landowner_" + selectedLandBuildingId).val(),
                Purpose: $("#land_building_purpose_" + selectedLandBuildingId).val(),
                LeaseRate: $("#land_building_lease_Rate_" + selectedLandBuildingId).val(),
                Coordinate: $("#land_building_coordinate_" + selectedLandBuildingId).val(),
                Phone: $("#land_building_phone_" + selectedLandBuildingId).val(),
            }

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

                toast_ok(rel.msg);

                powerStationData = rel.data;
                SetLandBuildingInfo();

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

        //#region 切換【電站基本資料】、【能源局與台電】等檢視或修改模式
        function ChangeMode(type, mode) {
            switch (type) {
                case "station_info": //【電站基本資料】
                    if (mode === "view") {
                        //觀看
                        $('#power_station_operation_personnel-error').hide();
                        $('#coordinate_text-error').hide();
                        //#region 電站基本資料 文字
                        $("#address_detail_text").show();

                        $("#power_station_code_text").show();
                        $("#power_station_name_text").show();
                        $("#escrow_name_text").show();

                        $("#generating_capacity_text").show();
                        $("#estimate_efficacy_text").show();
                        $("#estimate_kwh_text").show();
                        $("#estimated_recovery_time_text").show();

                        $("#coordinate_text").show();
                        $("#line_token_text").show();

                        $("#created_by_title").show();
                        $("#created_by_text").show();
                        $("#created_at_title").show();
                        $("#created_at_text").show();

                        //逆變器
                        $("#inverter_brand_text").show();
                        $("#inverter_product_model_text").show();
                        $("#inverter_amount_text").show();

                        //光電板
                        $("#photovoltaic_panel_brand_text").show();
                        $("#photovoltaic_panel_specification_text").show();
                        $("#photovoltaic_panel_amount_text").show();
                        $("#photovoltaic_panel_product_model_text").show();
                        //#endregion

                        //#region 電站基本資料 input
                        $("#select_city").attr("disabled", true);
                        $("#select_area").attr("disabled", true);
                        $("#address_detail").hide();
                        $("#address_detail").val(powerStationData.address);
                        $("#select_solar_tpye").attr("disabled", true);

                        $("#power_station_name").hide();
                        $("#power_station_name").val(powerStationData.name);
                        $("#check_escrow").attr("disabled", true);
                        $("#escrow_name").hide();


                        $("#generating_capacity").hide();
                        $("#generating_capacity").val(powerStationData.generatingCapacity);
                        $("#estimate_kwh").hide();
                        $("#estimate_kwh").val(powerStationData.estimate_kwh);
                        $("#estimate_efficacy").hide();
                        $("#estimate_efficacy").val(powerStationData.estimateEfficacy);
                        $("#estimated_recovery_time").hide();
                        $("#estimated_recovery_time").val(powerStationData.estimatedRecoveryTime);


                        $("#power_station_operation_personnel").attr("disabled", true);
                        $("#power_station_operation_personnel").val(powerStationData.operationPersonnelIds).trigger("change");

                        $("#coordinate").hide();
                        $("#coordinate").val(powerStationData.coordinate);
                        $("#line_token").hide();
                        $("#line_token").val(powerStationData.line_token);

                        @if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformUser)
                        {
                            <text>
                            $("#select_power_station_company_title").show();
                            $("#select_power_station_company").show();
                            $("#select_power_station_company").attr("disabled", true);
                            </text>
                        }
                        else
                        {
                            <text>
                            $("#select_power_station_company_title").hide();
                            $("#select_power_station_company").hide();
                            $("#select_power_station_company").attr("disabled", true);
                            </text>
                        }

                        //逆變器
                        $("#inverter_brand").hide();
                        $("#inverter_product_model").hide();
                        $("#inverter_amount").hide();

                        //光電板
                        $("#photovoltaic_panel_brand").hide();
                        $("#photovoltaic_panel_specification").hide();
                        $("#photovoltaic_panel_amount").hide();
                        $("#photovoltaic_panel_product_model").hide();
                        //#endregion

                        //#region 電站基本資料 btn
                        $("#add-station-info-btn").hide();
                        $("#edit-station-info-btn").show();
                        $("#canecl-station-info-btn").hide();
                        //#endregion
                    } else {
                        //修改
                        station_infocreate = true;
                        //#region 電站基本資料 文字
                        $("#address_detail_text").hide();

                        $("#power_station_name_text").hide();
                        $("#electricity_meter_at_text").hide();
                        $("#estimated_recovery_time_text").hide();
                        $("#created_by_title").hide();
                        $("#created_by_text").hide();

                        $("#generating_capacity_text").hide();
                        $("#escrow_name_text").hide();
                        $("#power_rate_text").hide();
                        $("#coordinate_text").hide();
                        $("#created_at_text").hide();
                        $("#created_at_title").hide();

                        $("#line_token_text").hide();
                        $("#estimate_kwh_text").hide();
                        $("#estimate_efficacy_text").hide();

                        //逆變器
                        $("#inverter_brand_text").hide();
                        $("#inverter_product_model_text").hide();
                        $("#inverter_amount_text").hide();

                        //光電板
                        $("#photovoltaic_panel_brand_text").hide();
                        $("#photovoltaic_panel_specification_text").hide();
                        $("#photovoltaic_panel_amount_text").hide();
                        $("#photovoltaic_panel_product_model_text").hide();
                        //#endregion

                        //#region 電站基本資料 input
                        $("#select_city").attr("disabled", true);
                        $("#select_area").attr("disabled", true);
                        $("#address_detail").show();
                        $("#select_solar_tpye").attr("disabled", false);

                        $("#power_station_name").show();
                        $("#check_escrow").attr("disabled", false);
                        $("#escrow_name").show();

                        $("#generating_capacity").show();
                        $("#estimate_kwh").show();
                        $("#estimate_efficacy").show();
                        $("#estimated_recovery_time").show();

                        $("#coordinate").show();
                        $("#line_token").show();

                        $("#power_station_operation_personnel").attr("disabled", false);

                        $("#power_station_operation_personnel > option").each(function () {
                            var canBeSelected = $(this).attr('data-canBeSelected');
                            var val = $(this).text();
                            if (canBeSelected == 1) {
                                $(this).attr("disabled", false);

                            } else {
                                $(this).attr("disabled", true);

                            }
                        });

                        $("#power_station_operation_personnel").select2();

                        $(".select2-selection__choice").each(function () {
                            var select2_text = this.title;
                            var select2 = this;

                            $("#power_station_operation_personnel > option").each(function () {
                                var xxx = $(this).text();
                                var canBeSelected = $(this).attr('data-canBeSelected');

                                if (select2_text == xxx) {
                                    if (canBeSelected == "1") {
                                        $(select2).children(".select2-selection__choice__remove").show();

                                    } else {
                                        $(select2).children(".select2-selection__choice__remove").hide();
                                    }
                                }
                            });
                        });

                        @if (ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformAdmin || ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.PlatformUser)
                        {
                            <text>
                            $("#select_power_station_company_title").show();
                            $("#select_power_station_company").show();
                            $("#select_power_station_company").attr("disabled", true);
                            </text>
                        }
                        else
                        {
                            <text>
                            $("#select_power_station_company_title").hide();
                            $("#select_power_station_company").hide();
                            $("#select_power_station_company").attr("disabled", true);
                            </text>
                        }

                        //逆變器
                        $("#inverter_brand").show();
                        $("#inverter_product_model").show();
                        $("#inverter_amount").show();

                        //光電板
                        $("#photovoltaic_panel_brand").show();
                        $("#photovoltaic_panel_specification").show();
                        $("#photovoltaic_panel_amount").show();
                        $("#photovoltaic_panel_product_model").show();
                        //#endregion

                        //#region 電站基本資料 btn
                        $("#add-station-info-btn").show();
                        $("#edit-station-info-btn").hide();
                        $("#canecl-station-info-btn").show();
                        //#endregion
                    }
                    break;
                case "BOE_TPC": //【能源局與台電】
                    if (mode === "view") {
                        //觀看
                        //#region 能源局與台電資料 文字
                        $("#link-boe-file").show();
                        @*$("#BoE_discount_rate_text").show();*@
                        @*$("#BoE_rent_ratio_text").show();*@
                        $("#BoE_register_post_at_text").show();
                        $("#BoE_device_register_number_text").show();

                        $("#TPC_contract_number_text").show();
                        $("#TPC_contract_at_text").show();
                        $("#TPC_sell_deadline_text").show();
                        $("#electricity_meter_at_text").show();
                        $("#power_rate_text").show();
                        $("#TPC_sell_electricity_at_text").show();
                        $("#TPC_invoice_buyer_text").show();
                        $("#GUI_number_text").show();
                        $("#TPC_invoice_address_text").show();
                        $("#TPC_meter_number_text").show();
                        @*$("#TPC_meter_reading_text").show();*@
                        @*$("#TPC_purchase_electricity_at_text").show();*@

                        $("#BOE_TPC_created_by_title").show();
                        $("#BOE_TPC_created_by_text").show();
                        $("#BOE_TPC_created_at_title").show();
                        $("#BOE_TPC_created_at_text").show();
                        //#endregion

                        //#region 能源局與台電資料 input
                        $("#BoE_file").hide();
                        $("#BoE_register_post_at").hide();
                        $("#BoE_device_register_number").hide();
                        @*$("#BoE_discount_rate").hide();*@
                        @*$("#BoE_rent_ratio").hide();*@

                        $("#TPC_contract_number").hide();
                        $("#TPC_contract_at").hide();
                        $("#TPC_sell_deadline").hide();
                        $("#electricity_meter_at").hide();
                        $("#power_rate").hide();
                        $("#TPC_sell_electricity_at").hide();
                        $("#TPC_invoice_buyer").hide();
                        $("#GUI_number").hide();
                        $("#TPC_invoice_address").hide();
                        $("#TPC_meter_number").hide();
                        @*$("#TPC_meter_reading").hide();*@
                        @*$("#TPC_purchase_electricity_at").hide();*@
                        //#endregion

                        //#region 能源局與台電btn
                        $("#add-boe-tpc-btn").hide();
                        $("#edit-boe-tpc-btn").show();
                        $("#canecl-boe-tpc-btn").hide();
                        //#endregion
                    } else {
                        //修改
                        //#region 能源局與台電資料 文字
                        $("#link-boe-file").hide();
                        @*$("#BoE_discount_rate_text").hide();*@
                        $("#BoE_register_post_at_text").hide();
                        $("#BoE_device_register_number_text").hide();
                        @*$("#BoE_rent_ratio_text").hide();*@

                        $("#TPC_contract_number_text").hide();
                        $("#TPC_contract_at_text").hide();
                        $("#TPC_sell_deadline_text").hide();
                        $("#electricity_meter_at_text").hide();
                        $("#power_rate_text").hide();
                        $("#TPC_sell_electricity_at_text").hide();
                        $("#TPC_invoice_buyer_text").hide();
                        $("#GUI_number_text").hide();
                        $("#TPC_invoice_address_text").hide();
                        $("#TPC_meter_number_text").hide();

                        $("#BOE_TPC_created_by_title").hide();
                        $("#BOE_TPC_created_by_text").hide();
                        $("#BOE_TPC_created_at_title").hide();
                        $("#BOE_TPC_created_at_text").hide();
                        //#endregion

                        //#region 能源局與台電資料 input
                        $("#BoE_file").show();
                        @*$("#BoE_discount_rate").show();*@
                        $("#BoE_register_post_at").show();
                        $("#BoE_device_register_number").show();
                        @*$("#BoE_rent_ratio").show();*@

                        $("#TPC_contract_number").show();
                        $("#TPC_contract_at").show();
                        $("#TPC_sell_deadline").show();
                        $("#electricity_meter_at").show();
                        $("#power_rate").show();
                        $("#TPC_sell_electricity_at").show();
                        $("#TPC_invoice_buyer").show();
                        $("#GUI_number").show();
                        $("#TPC_invoice_address").show();
                        $("#TPC_meter_number").show();
                        //#endregion

                        //#region 能源局與台電btn
                        $("#add-boe-tpc-btn").show();
                        $("#edit-boe-tpc-btn").hide();
                        $("#canecl-boe-tpc-btn").show();
                        //#endregion
                    }
                    break;
                case "land_building_info": //【土地房屋資料】
                    if (mode === "view") {
                        //觀看
                        //#region 土地房屋資料 文字
                        $("#land_building_address_text_" + selectedLandBuildingId).show();
                        @*$("#land_building_coordinate_text_" + selectedLandBuildingId).show();*@
                        $("#lease_notarization_at_text_" + selectedLandBuildingId).show();
                        $("#land_building_lease_Rate_text_" + selectedLandBuildingId).show();
                        $("#land_building_landowner_text_" + selectedLandBuildingId).show();
                        @*$("#land_building_phone_text_" + selectedLandBuildingId).show();*@
                        @*$("#land_building_purpose_text_" + selectedLandBuildingId).show();*@
                        $("#land_building_created_by_title_" + selectedLandBuildingId).show();
                        $("#land_building_created_by_text_" + selectedLandBuildingId).show();
                        $("#land_building_created_at_title_" + selectedLandBuildingId).show();
                        $("#land_building_created_at_text_" + selectedLandBuildingId).show();
                        //#endregion

                        //#region 土地房屋資料 input
                        $("#land_building_address_" + selectedLandBuildingId).hide();
                        @*$("#land_building_coordinate_" + selectedLandBuildingId).hide();*@
                        $("#lease_notarization_at_" + selectedLandBuildingId).hide();
                        $("#land_building_lease_Rate_" + selectedLandBuildingId).hide();
                        $("#land_building_landowner_" + selectedLandBuildingId).hide();
                        @*$("#land_building_phone_" + selectedLandBuildingId).hide();*@
                        @*$("#land_building_purpose_" + selectedLandBuildingId).hide();*@
                        //#endregion

                        //#region 土地房屋資料 btn
                        $("#save-land-building-info-btn-" + selectedLandBuildingId).hide();
                        $("#edit-land-building-info-btn-" + selectedLandBuildingId).show();
                        $("#canecl-land-building-info-btn-" + selectedLandBuildingId).hide();
                        $("#del-land-building-info-btn-" + selectedLandBuildingId).show();
                        //#endregion
                    } else {
                        //修改
                        //#region 土地房屋資料 文字
                        $("#land_building_address_text_" + selectedLandBuildingId).hide();
                        @*$("#land_building_coordinate_text_" + selectedLandBuildingId).hide();*@
                        $("#lease_notarization_at_text_" + selectedLandBuildingId).hide();
                        $("#land_building_lease_Rate_text_" + selectedLandBuildingId).hide();
                        $("#land_building_landowner_text_" + selectedLandBuildingId).hide();
                        @*$("#land_building_phone_text_" + selectedLandBuildingId).hide();*@
                        @*$("#land_building_purpose_text_" + selectedLandBuildingId).hide();*@
                        $("#land_building_created_by_title_" + selectedLandBuildingId).hide();
                        $("#land_building_created_by_text_" + selectedLandBuildingId).hide();
                        $("#land_building_created_at_title_" + selectedLandBuildingId).hide();
                        $("#land_building_created_at_text_" + selectedLandBuildingId).hide();
                        //#endregion

                        //#region 土地房屋資料 input
                        $("#land_building_address_" + selectedLandBuildingId).show();
                        @*$("#land_building_coordinate_" + selectedLandBuildingId).show();*@
                        $("#lease_notarization_at_" + selectedLandBuildingId).show();
                        $("#land_building_lease_Rate_" + selectedLandBuildingId).show();
                        $("#land_building_landowner_" + selectedLandBuildingId).show();
                        @*$("#land_building_phone_" + selectedLandBuildingId).show();*@
                        @*$("#land_building_purpose_" + selectedLandBuildingId).show();*@
                        //#endregion

                        //#region 土地房屋資料 btn
                        $("#save-land-building-info-btn-" + selectedLandBuildingId).show();
                        $("#edit-land-building-info-btn-" + selectedLandBuildingId).hide();
                        $("#canecl-land-building-info-btn-" + selectedLandBuildingId).show();
                        $("#del-land-building-info-btn-" + selectedLandBuildingId).hide();
                        //#endregion
                    }
                    break;
            }
        }
        //#endregion

        $('#power_station_operation_personnel').on('select2:closing', function (e) {
            $(".select2-selection__choice").each(function () {
                var select2_text = this.title;
                var select2 = this;

                $("#power_station_operation_personnel > option").each(function () {
                    var xxx = $(this).text();
                    var canBeSelected = $(this).attr('data-canBeSelected');

                    if (select2_text == xxx) {
                        if (canBeSelected == "1") {
                            $(select2).children(".select2-selection__choice__remove").show();

                        } else {
                            $(select2).children(".select2-selection__choice__remove").hide();
                        }
                    }
                });
            });
        });




        //#region 設定電站基本資料
        function SetStationInfo() {

            $("#power-station-title").html(powerStationData.name);

            $("#select_city").val(powerStationData.cityId).trigger("change");
            $("#select_area").val(powerStationData.areaId);
            $("#select_solar_tpye").val(powerStationData.solarType);

            //#region 電站基本資料 文字
            $("#address_detail_text").html(powerStationData.address);
            $("#power_station_code_text").html(powerStationData.code);
            $("#power_station_name_text").html(powerStationData.name);

            $("#estimated_recovery_time_text").html(powerStationData.estimatedRecoveryTime);
            $("#created_by_text").html(powerStationData.creatorName);

            $("#generating_capacity_text").html(powerStationData.generatingCapacity.toFixed(3));
            $("#escrow_name_text").html(powerStationData.escrowName);
            $("#coordinate_text").html(powerStationData.coordinate);
            $("#created_at_text").html(powerStationData.createdAt);
            $("#power_station_operation_personnel").val(powerStationData.operationPersonnelIds).trigger("change");

            $("#line_token_text").html(powerStationData.line_token);
            $("#estimate_kwh_text").html(powerStationData.estimate_kwh);
            $("#estimate_efficacy_text").html(powerStationData.estimateEfficacy);

            $("#select_power_station_company").val(powerStationData.companyId).trigger("change");

            //逆變器
            $("#inverter_brand_text").html(powerStationData.inverterBrand);
            $("#inverter_product_model_text").html(powerStationData.inverterProductModel);
            $("#inverter_amount_text").html(powerStationData.inverterAmount);

            //光電板
            $("#photovoltaic_panel_brand_text").html(powerStationData.photovoltaicPanelBrand);
            $("#photovoltaic_panel_product_model_text").html(powerStationData.photovoltaicPanelProductModel);
            $("#photovoltaic_panel_specification_text").html(powerStationData.photovoltaicPanelSpecification);
            $("#photovoltaic_panel_amount_text").html(powerStationData.photovoltaicPanelAmount);
            //#endregion

            //#region 電站基本資料 input
            $("#address_detail").val(powerStationData.address);
            $("#power_station_name").val(powerStationData.name);
            $("#check_escrow").attr("checked", powerStationData.isEscrow == 1 ? true : false);
            $("#check_escrow_label").html(powerStationData.isEscrow == 1 ? "Yes" : "No");
            $("#electricity_meter_at").val(powerStationData.electricityMeterAt);
            $("#estimated_recovery_time").val(powerStationData.estimatedRecoveryTime);

            $("#generating_capacity").val(powerStationData.generatingCapacity);
            $("#escrow_name").val(powerStationData.escrowName);
            $("#power_rate").val(powerStationData.powerRate);
            $("#coordinate").val(powerStationData.coordinate);

            $("#line_token").val(powerStationData.line_token);
            $("#estimate_kwh").val(powerStationData.estimate_kwh);
            $("#estimate_efficacy").val(powerStationData.estimateEfficacy);

            //逆變器
            $("#inverter_brand").val(powerStationData.inverterBrand);
            $("#inverter_product_model").val(powerStationData.inverterProductModel);
            $("#inverter_amount").val(powerStationData.inverterAmount);

            //光電板
            $("#photovoltaic_panel_brand").val(powerStationData.photovoltaicPanelBrand);
            $("#photovoltaic_panel_product_model").val(powerStationData.photovoltaicPanelProductModel);
            $("#photovoltaic_panel_specification").val(powerStationData.photovoltaicPanelSpecification);
            $("#photovoltaic_panel_amount").val(powerStationData.photovoltaicPanelAmount);
            //#endregion
        }
        //#endregion

        //#region 設定能源局與台電資料
        function SetBoETPCInfo() {
            //#region 能源局與台電資料 文字
            $("#link-boe-file").html(powerStationData.boEFileName).attr("href", powerStationData.boEFile);
            @*$("#BoE_discount_rate_text").html(powerStationData.boEDiscountRate);*@
            $("#BoE_register_post_at_text").html(powerStationData.boERegisterPostAt);
            $("#BoE_device_register_number_text").html(powerStationData.boEDeviceRegisterNumber);
            @*$("#BoE_rent_ratio_text").html(powerStationData.boERentRatio);*@

            $("#TPC_contract_number_text").html(powerStationData.tpcContractNumber);
            $("#TPC_contract_at_text").html(powerStationData.tpcContractAt);
            $("#TPC_sell_deadline_text").html(powerStationData.tpcSellDeadline);
            $("#electricity_meter_at_text").html(powerStationData.electricityMeterAt);
            $("#power_rate_text").html(powerStationData.powerRate);
            $("#TPC_meter_reading_text").html(powerStationData.tpcMeterReading);
            $("#TPC_purchase_electricity_at_text").html(powerStationData.tpcPurchaseElectricityAt);
            $("#TPC_sell_electricity_at_text").html(powerStationData.tpcSellElectricityAt);
            $("#TPC_invoice_buyer_text").html(powerStationData.tpcInvoiceBuyer);
            $("#GUI_number_text").html(powerStationData.guiNumber);
            $("#TPC_invoice_address_text").html(powerStationData.tpcInvoiceAddress);
            $("#TPC_meter_number_text").html(powerStationData.tpcMeterNumber);

            $("#BOE_TPC_created_by_text").html(powerStationData.creatorName);
            $("#BOE_TPC_created_at_text").html(powerStationData.createdAt);
            //#endregion

            //#region 能源局與台電資料 input
            @*$("#BoE_discount_rate").val(powerStationData.boEDiscountRate);*@
            $("#BoE_register_post_at").val(powerStationData.boERegisterPostAt);
            $("#BoE_device_register_number").val(powerStationData.boEDeviceRegisterNumber);
            @*$("#BoE_rent_ratio").val(powerStationData.boERentRatio);*@

            $("#TPC_contract_number").val(powerStationData.tpcContractNumber);
            $("#TPC_contract_at").val(powerStationData.tpcContractAt);
            $("#TPC_sell_deadline").val(powerStationData.tpcSellDeadline);
            $("#electricity_meter_at").val(powerStationData.electricityMeterAt);
            $("#power_rate").val(powerStationData.powerRate);
            $("#TPC_meter_reading").val(powerStationData.tpcMeterReading);
            $("#TPC_purchase_electricity_at").val(powerStationData.tpcPurchaseElectricityAt);
            $("#TPC_sell_electricity_at").val(powerStationData.tpcSellElectricityAt);
            $("#TPC_invoice_buyer").val(powerStationData.tpcInvoiceBuyer);
            $("#GUI_number").val(powerStationData.guiNumber);
            $("#TPC_invoice_address").val(powerStationData.tpcInvoiceAddress);
            $("#TPC_meter_number").val(powerStationData.tpcMeterNumber);
            //#endregion
        }
        //#endregion

        //#region 設定土地與房屋資料
        function SetLandBuildingInfo() {
            var landBuildingCard = $("#land_buildingPart");

            landBuildingCard.empty();
            powerStationData.landBuildings.forEach(function (value, index) {
                CreateLandBuildingCard(landBuildingCard, value);
            });

            // 找出第一個移除"刪除"按鈕
            var firstCardId = landBuildingCard.find(".card").first().attr("data-land-building-id");
            $("#del-land-building-info-btn-" + firstCardId).remove();

            //加入新增土地房屋卡片
            CreateAddLandBuildingCard(landBuildingCard);
        }
        //#endregion

        //#region 創建每份土地房屋資訊卡片
        function CreateLandBuildingCard(dom, value) {

            //資料重整
            value.address = value.address ? value.address : '';
            value.coordinate = value.coordinate ? value.coordinate : '';
            value.leaseNotarizationAt = value.leaseNotarizationAt ? value.leaseNotarizationAt : '';
            value.leaseRate = value.leaseRate ? value.leaseRate : 0;
            value.landowner = value.landowner ? value.landowner : '';
            value.phone = value.phone ? value.phone : '';
            value.purpose = value.purpose ? value.purpose : '';

            var appendStr = "";
            appendStr += '<div class="card border mb-g w-100" data-land-building-id="' + value.id + '">' +
                '<div class="card-header bg-fusion-25 py-2 pr-3 d-flex align-items-center flex-wrap justify-content-between">' +
                '<div class="card-title font-weight-bold">土地房屋資料</div>' +
                '<div class="text-right">' +
                '<button class="btn btn-sm btn-warning ml-auto waves-effect waves-themed save-land-building-info-btn" style="display:none" data-land-building-id="' + value.id + '" id="save-land-building-info-btn-' + value.id + '">' +
                '<span class="fal fa-save mr-1"></span> 儲存' +
                '</button>' +
                '<button class="btn btn-sm btn-info ml-auto waves-effect waves-themed edit-land-building-info-btn" data-land-building-id="' + value.id + '" id="edit-land-building-info-btn-' + value.id + '">' +
                '<span class="fal fa-cog mr-1"></span> 修改' +
                '</button>' +
                '<button class="btn btn-sm btn-dark ml-auto waves-effect waves-themed canecl-land-building-info-btn" style="display:none" data-land-building-id="' + value.id + '" id="canecl-land-building-info-btn-' + value.id + '">' +
                '<span class="fal fa-redo mr-1"></span> 取消' +
                '</button>' +
                '<button class="btn btn-sm btn-danger ml-auto waves-effect waves-themed del-land-building-info-btn" data-land-building-id="' + value.id + '" id="del-land-building-info-btn-' + value.id + '">' +
                '<span class="fal fa-trash-alt mr-1"></span> 刪除' +
                '</button>' +
                '</div>' +
                '</div>';

            appendStr += '<div class="card-body">' +
                '<div class="row d-flex justify-content-between card-land-building" data-id="' + value.id + '">' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">地址</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_address_text_' + value.id + '" class="color-info-600">' + value.address + '</label>' +
                '<input type="text" style="display:none" id="land_building_address_' + value.id + '" name="land_building_address_' + value.id + '" class="form-control" value="' + value.address + '">' +
                '</div>' +
                '</div>' +
                '<div class="row">' +
                '<label class="col-xl-4 form-label">租金比例 (%)</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_lease_Rate_text_' + value.id + '" class="color-info-600">' + value.leaseRate + '</label>' +
                '<input type="number" step="0.1" style="display:none" id="land_building_lease_Rate_' + value.id + '" name="land_building_lease_Rate_' + value.id + '" class="form-control" value="' + value.leaseRate + '">' +
                '</div>' +
                '</div>' +
                @*'<div class="row">' +
                '<label class="col-xl-4 form-label">經緯度</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_coordinate_text_' + value.id + '" class="color-info-600">' + value.coordinate + '</label>' +
                '<input type="text" style="display:none" id="land_building_coordinate_' + value.id + '" name="land_building_coordinate_' + value.id + '" class="form-control" value="' + value.coordinate + '">' +
                '</div>' +
                '</div>' +*@
                '</div>' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">租約公證日期</label>' +
                '<div class="col-xl-8">' +
                '<label id="lease_notarization_at_text_' + value.id + '" class="color-info-600">' + value.leaseNotarizationAt + '</label>' +
                '<input type="date" style="display:none" id="lease_notarization_at_' + value.id + '" name="lease_notarization_at_' + value.id + '" class="form-control" value="' + value.leaseNotarizationAt + '">' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">出租人</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_landowner_text_' + value.id + '" class="color-info-600">' + value.landowner + '</label>' +
                '<input type="text" style="display:none" id="land_building_landowner_' + value.id + '" name="land_building_landowner_' + value.id + '" class="form-control" value="' + value.landowner + '">' +
                '</div>' +
                '</div>' +
                @*'<div class="row">' +
                '<label class="col-xl-4 form-label">電話</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_phone_text_' + value.id + '" class="color-info-600">' + value.phone + '</label>' +
                '<input type="text" style="display:none" id="land_building_phone_' + value.id + '" name="land_building_phone_' + value.id + '" class="form-control" value="' + value.phone + '">' +
                '</div>' +
                '</div>' +*@
                '</div>' +
                '<div class="col-xl">' +
                @*'<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">房屋用途</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_purpose_text_' + value.id + '" class="color-info-600">' + value.purpose + '</label>' +
                '<input type="text" style="display:none" id="land_building_purpose_' + value.id + '" name="land_building_purpose_' + value.id + '" class="form-control" value="' + value.purpose + '">' +
                '</div>' +
                '</div>' +*@
                '</div>' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label" id="land_building_created_by_title_' + value.id + '">資料建立</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_created_by_text_' + value.id + '" class="color-info-600">' + value.creatorName + '</label>' +
                '</div>' +
                '</div>' +
                '<div class="row">' +
                '<label class="col-xl-4 form-label" id="land_building_created_at_title_' + value.id + '">建立時間</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_created_at_text_' + value.id + '" class="color-info-600">' + value.createdAt + '</label>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';

            dom.append(appendStr);
        }
        //#endregion

        //#region 創建新增土地房屋資訊卡片
        function CreateAddLandBuildingCard(dom) {
            var appendStr = "";
            appendStr += '<div class="card border mb-g w-100" id="add-land-building-card">' +
                '<div class="card-header bg-fusion-25 py-2 pr-3 d-flex align-items-center flex-wrap justify-content-between">' +
                '<div class="card-title font-weight-bold">土地房屋資料</div>' +
                '<div class="text-right">' +
                '<button class="btn btn-sm btn-success ml-auto waves-effect waves-themed" id="add-land-building-info-btn">' +
                '<span class="fal fa-plus mr-1"></span> 新增' +
                '</button>' +
                '<div aria-expanded="true">' +
                '<button class="btn btn-sm btn-warning ml-auto waves-effect waves-themed save-land-building-info-btn" style="display:none" data-land-building-id="0" id="save-land-building-info-btn-0">' +
                '<span class="fal fa-save mr-1"></span> 儲存' +
                '</button>' +
                '<button class="btn btn-sm btn-dark ml-auto waves-effect waves-themed" style="display:none" id="cancel-add-land-building-info-btn">' +
                '<span class="fal fa-redo mr-1"></span> 取消' +
                '</button>' +
                '</div>' +
                '</div>' +
                '</div>';

            appendStr += '<div class="card-body collapse">' +
                '<div class="row d-flex justify-content-between card-land-building">' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">地址</label>' +
                '<div class="col-xl-8">' +
                '<input type="text" id="land_building_address_0" name="land_building_address_0" class="form-control">' +
                '</div>' +
                '</div>' +
                '<div class="row">' +
                '<label class="col-xl-4 form-label">租金比例 (%)</label>' +
                '<div class="col-xl-8">' +
                '<input type="text" step="0.01" id="land_building_lease_Rate_0" name="land_building_lease_Rate_0" class="form-control">' +
                '</div>' +
                '</div>' +
                @*'<div class="row">' +
                '<label class="col-xl-4 form-label">經緯度</label>' +
                '<div class="col-xl-8">' +
                '<input type="text" id="land_building_coordinate_0" name="land_building_coordinate_0" class="form-control">' +
                '</div>' +
                '</div>' +*@
                '</div>' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">租約公證日期</label>' +
                '<div class="col-xl-8">' +
                '<input type="date" id="lease_notarization_at_0" name="lease_notarization_at_0" class="form-control">' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">出租人</label>' +
                '<div class="col-xl-8">' +
                '<input type="text" id="land_building_landowner_0" name="land_building_landowner_0" class="form-control">' +
                '</div>' +
                '</div>' +
                @*'<div class="row">' +
                '<label class="col-xl-4 form-label">電話</label>' +
                '<div class="col-xl-8">' +
                '<input type="text" id="land_building_phone_0" name="land_building_phone_0" class="form-control">' +
                '</div>' +
                '</div>' +*@
                '</div>' +
                '<div class="col-xl">' +
                @*'<div class="row mb-3">' +
                '<label class="col-xl-4 form-label">房屋用途</label>' +
                '<div class="col-xl-8">' +
                '<input type="text" id="land_building_purpose_0" name="land_building_purpose_0" class="form-control">' +
                '</div>' +
                '</div>' +*@
                '</div>' +
                '<div class="col-xl">' +
                '<div class="row mb-3">' +
                '<label class="col-xl-4 form-label" id="land_building_created_by_title_0">資料建立</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_created_by_text_0" class="color-info-600"></label>' +
                '</div>' +
                '</div>' +
                '<div class="row">' +
                '<label class="col-xl-4 form-label" id="land_building_created_at_title_0">建立時間</label>' +
                '<div class="col-xl-8">' +
                '<label id="land_building_created_at_text_0" class="color-info-600"></label>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';

            dom.append(appendStr);
        }
        //#endregion

        //#region 土地與房屋按鈕控制
        //儲存
        $('#land_buildingPart').on("click", "button.save-land-building-info-btn", function () {
            selectedLandBuildingId = $(this).attr("data-land-building-id");

            SaveLandBuildingInfo();
            isLandBuildingLock = false;
        });

        //編輯
        $('#land_buildingPart').on("click", "button.edit-land-building-info-btn", function () {
            if (isLandBuildingLock) {
                toast_error("當前已有其他【土地方屋資訊】正在編輯中。")
            }
            selectedLandBuildingId = $(this).attr("data-land-building-id");

            ChangeMode("land_building_info", "edit");
            isLandBuildingLock = true;
        });

        //取消
        $('#land_buildingPart').on("click", "button.canecl-land-building-info-btn", function () {
            selectedLandBuildingId = $(this).attr("data-land-building-id");

            ChangeMode("land_building_info", "view");
            isLandBuildingLock = false;
        });

        //刪除
        $('#land_buildingPart').on("click", "button.del-land-building-info-btn", function () {
            selectedLandBuildingId = $(this).attr("data-land-building-id");
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/PowerStation/DeleteLandBuildingInfo";
                        var send_data = {
                            SelectedId: selectedLandBuildingId,
                            PowerStationId: stationId
                        }
                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            powerStationData = rel.data;
                            SetLandBuildingInfo();
                        }, 'json');
                    }
                });
        });

        //新增土地房屋卡片
        //新增
        $('#land_buildingPart').on("click", "#add-land-building-card button#add-land-building-info-btn", function () {
            $("#add-land-building-card > .card-body").collapse('show');

            $("#add-land-building-card button#add-land-building-info-btn").hide();
            $("#add-land-building-card button#save-land-building-info-btn-0").show();
            $("#add-land-building-card button#cancel-add-land-building-info-btn").show();
        });

        //取消
        $('#land_buildingPart').on("click", "#add-land-building-card button#cancel-add-land-building-info-btn", function () {
            $("#add-land-building-card > .card-body").collapse('hide');

            $("#add-land-building-card button#add-land-building-info-btn").show();
            $("#add-land-building-card button#save-land-building-info-btn-0").hide();
            $("#add-land-building-card button#cancel-add-land-building-info-btn").hide();
        });
        //#endregion

        //#region 新增維運資料
        function AddOperation()
        {
            selected_id = 0;

            $("#Operation-modal .modal-title").html("運維廠商資料 - 新增");
            $("#Operation-form").trigger("reset");
            $("#Operation-modal").modal();
        }
        //#endregion

        //#region 儲存運維資料
        function SaveOperation() {
            if ($("#Operation-form").valid()) {
                var url = "/PowerStation/SaveOperation";
                var send_data = {
                    Id: selected_id,
                    PowerStationId: stationId,
                    Type: $("#Operation_role_modal").val(),
                    Name: $("#Operation_factory_modal").val(),
                    ContactPerson: $("#Operation_name_modal").val(),
                    Phone: $("#Operation_phone_modal").val(),
                    Email: $("#Operation_email_modal").val(),
                    TaxIDNumber: $("#Operation_taxIDNumber_modal").val(),
                    Remark: $("#Operation_remark_modal").val(),
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    else
                    {
                        toast_ok(rel.msg);
                        $('#Operation-modal').modal('hide');
                        OperationTable.ajax.reload();
                        return;
                    }

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

        //#region 儲存共享設備
        function SaveShareDevice() {
            if ($("#Operation-form").valid()) {
                var url = "/PowerStation/SaveShareDevice";
                var send_data = {
                    Id: selected_id,
                    PowerStationId: stationId,
                    DeviceId: $("#ShareDevice_UID_modal").val()
                }

                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        $('#ShareDevice-modal').modal('hide');
                        ShareDeviceTable.ajax.reload();
                        return;
                    }

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

        //#region 取一筆運維
        $('#Operation_table').on("click", "button.edit-btn", function () {
            $("#Operation-modal .modal-title").html("運維廠商資料 - 編輯");

            selected_id = $(this).parents('tr').attr('data-id');

            //取得單一運維基本資料
            var url = "/PowerStation/GetOneOperation/";

            var send_data = {
                SelectedId: selected_id,
                PowerStationId: stationId
            }

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

                $("#Operation_role_modal").val(rel.data.type);
                $("#Operation_factory_modal").val(rel.data.name);
                $("#Operation_name_modal").val(rel.data.contactPerson);
                $("#Operation_phone_modal").val(rel.data.phone);
                $("#Operation_email_modal").val(rel.data.email);
                $("#Operation_taxIDNumber_modal").val(rel.data.taxIDNumber);
                $("#Operation_remark_modal").val(rel.data.remark);

                $("#Operation-modal").modal();
            }, 'json');

        });
        //#endregion

        //#region 刪除運維資料
        $('#Operation_table').on("click", "button.del-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/PowerStation/DeleteOneOperation/";

                        var send_data = {
                            SelectedId: selected_id,
                            PowerStationId: stationId
                        }

                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            OperationTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 新增控制器資料
        function AddController() {
            selected_id = 0;
            $("#Controller-modal .modal-title").html("控制器資料 - 新增");
            $("#Controller-form").trigger("reset");
            $("#Controller-modal").modal();
        }
        //#endregion

        //#region 新增逆變器資料
        function AddInverter() {
            selected_id = 0;
            $("#Inverter-modal .modal-title").html("逆變器資料 - 新增");
            $("#Inverter-form").trigger("reset");

            document.getElementById('Inverter_Status_modal').disabled = true;
            document.getElementById('Inverter_Enabled_modal').disabled = true;
            PyrheliometerList(stationId);
            $("#Inverter-modal").modal();
        }
        //#endregion

        //#region 新增裝置資料
        function AddDevice() {
            selected_id = 0;
            document.getElementById('Device_Type_modal').disabled = false;
            document.getElementById('Device_Status_modal').disabled = true;
            document.getElementById('Device_Enabled_modal').disabled = true;
            $("#Device-modal .modal-title").html("裝置資料 - 新增");
            $("#Device-form").trigger("reset");
            $("#Device_TableName_modal").val("s" + $("#Device_Controller_modal").text() + "_sensoravg");
            $("#Device-modal").modal();
        }
        //#endregion

        //#region 新增共用裝置資料
        function AddShareDevice() {
            selected_id = 0;
            $("#ShareDevice-modal .modal-title").html("共用裝置資料 - 新增");
            $("#ShareDevice-form").trigger("reset");
            $("#ShareDevice-modal").modal();
        }
        //#endregion

        //#region 刪除共用裝置資料
        $('#ShareDevice_table').on("click", "button.del-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/PowerStation/DeleteOneShareDevice/";

                        var send_data = {
                            SelectedId: selected_id,
                            PowerStationId: stationId
                        }

                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            ShareDeviceTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 儲存控制器資料
        function SaveController() {
            var url = "/PowerStation/SaveController";
            if ($("#Controller-form").valid()) {
                var send_data = {
                    Id: selected_id,
                    PowerStationId: stationId,
                    Count: $("#Controller_Count_modal").val(),
                }
                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        $('#Controller-modal').modal('hide');
                        DeviceControllerTable.ajax.reload();
                        return;
                    }
                }, 'json');
            }
        }
        //#endregion

        //#region 刪除控制器資料
        $('#Controller_table').on("click", "button.del-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/PowerStation/DeleteOneDeviceController/";

                        var send_data = {
                            SelectedId: selected_id,
                            PowerStationId: stationId
                        }

                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            DeviceControllerTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 刪除逆變器資料
        $('#Inverter_table').on("click", "button.del-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/PowerStation/DeleteOneInverter/";

                        var send_data = {
                            SelectedId: selected_id,
                            PowerStationId: stationId
                        }

                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            InverterTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 儲存逆變器資料
        function SaveInverter() {

            var url = "/PowerStation/SaveInverter";
            if ($("#Inverter-form").valid()) {
                var send_data = {
                    ControllerId: $("#Inverter_ControllerId_modal").val(),
                    InverterName: $("#Inverter_InverterName_modal").val(),
                    InstallDate: $("#Inverter_InstallDate_modal").val(),
                    Brand: $("#Inverter_Brand_modal").val(),
                    BrandNum: $("#Inverter_BrandNum_modal").val(),
                    Model: $("#Inverter_Model_modal").val(),
                    Capacity: $("#Inverter_Capacity_modal").val(),
                    Pyrheliometer: $("#Inverter_Pyrheliometer_modal").val(),
                    Status: $("#Inverter_Status_modal").val(),
                    Enabled: $("#Inverter_Enabled_modal").val(),
                    WarrantyDate: $("#Inverter_WarrantyDate_modal").val(),
                    PowerStationId: stationId,
                    Id: selected_id,
                }
                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        $('#Inverter-modal').modal('hide');
                        InverterTable.ajax.reload();
                        return;
                    }
                }, 'json');
            }
        }
        //#endregion

        //#region 儲存裝置資料
        function SaveDevice() {

            if ($("#Device-form").valid()) {
                var url = "/PowerStation/SaveDevice";
                var a = padLeft($("#Device_ColName_modal").val(), 2);
                var send_data = {
                    Id: selected_id,
                    PowerStationId: stationId,
                    Name: $("#Device_Name_modal").val(),
                    ControllerId: $("#Device_Controller_modal").val(),
                    Type: $("#Device_Type_modal").val(),
                    TypeName: $("#Device_Type_modal :selected").text(),
                    Brand: $("#Device_Brand_modal").val(),
                    ProductModel: $("#Device_ProductModel_modal").val(),
                    //DBName: $("#Device_DBName_modal").val(),
                    TableName: $("#Device_TableName_modal").val(),
                    ColName: "SENSORAVG" + a,
                    InstallDate: $("#Device_InstallDate_modal").val(),
                    Status: $("#Device_Status_modal").val(),
                    Enabled: $("#Device_Enabled_modal").val(),
                    WarrantyDate: $("#Device_WarrantyDate_modal").val(),
                    BrandNum: $("#Device_BrandNum_modal").val()
                }
                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        $('#Device-modal').modal('hide');
                        DeviceTable.ajax.reload();
                        return;
                    }


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

        //#region 取一筆設備
        $('#Device_table').on("click", "button.edit-btn", function () {
            $("#Device-modal .modal-title").html("設備資料 - 編輯");
            document.getElementById('Device_Status_modal').disabled = true;
            selected_id = $(this).parents('tr').attr('data-id');

            //取得單一運維基本資料
            var url = "/PowerStation/GetOneDevice/";

            var send_data = {
                SelectedId: selected_id,
                PowerStationId: stationId,
            }


            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                document.getElementById('Device_Type_modal').disabled = true;
                document.getElementById('Device_Enabled_modal').disabled = false;
                $("#Device_Type_modal").val(rel.data.type);
                $("#Device_Brand_modal").val(rel.data.brand);
                $("#Device_ProductModel_modal").val(rel.data.productModel);
                //$("#Device_DBName_modal").val(rel.data.dbName);
                $("#Device_TableName_modal").val(rel.data.tableName);
                var colNameNum = null;
                if (rel.data.colName != null) {
                    colNameNum = rel.data.colName.substr(9, 2);
                }
                $("#Device_ColName_modal").val(colNameNum);
                $("#Device_Controller_modal").val(rel.data.controllerId);
                $("#Device_Name_modal").val(rel.data.name);
                $("#Device_Status_modal").val(rel.data.status);
                $("#Device_Enabled_modal").val(rel.data.enabled);
                $("#Device_InstallDate_modal").val(rel.data.installDate);
                $("#Device_BrandNum_modal").val(rel.data.brandNum);
                if (rel.data.warrantyDate != "0001-01-01") {
                    $("#Device_WarrantyDate_modal").val(rel.data.warrantyDate);
                } else {
                    $("#Device_WarrantyDate_modal").val(null);
                }


                $("#Device-modal").modal();
            }, 'json');

        });
        //#endregion

        //#region 取一筆逆變器
        $('#Inverter_table').on("click", "button.edit-btn", function () {
            $("#Inverter-modal .modal-title").html("逆變器 - 編輯");
            document.getElementById('Inverter_Status_modal').disabled = true;
            selected_id = $(this).parents('tr').attr('data-id');
            var url = "/PowerStation/GetOneInverter/";

            var send_data = {
                SelectedId: selected_id,
                PowerStationId: stationId,
            }
            PyrheliometerList(stationId);

            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                document.getElementById('Inverter_Enabled_modal').disabled = false;
                $("#Inverter_ControllerId_modal").val(rel.data.controllerId);
                $("#Inverter_InverterName_modal").val(rel.data.inverterName);
                $("#Inverter_InstallDate_modal").val(rel.data.installDate);
                $("#Inverter_Brand_modal").val(rel.data.brand);
                $("#Inverter_BrandNum_modal").val(rel.data.brandNum);
                $("#Inverter_Model_modal").val(rel.data.model);
                $("#Inverter_Capacity_modal").val(rel.data.capacity);
                $("#Inverter_Pyrheliometer_modal").val(rel.data.pyrheliometer);
                $("#Inverter_Status_modal").val(rel.data.status);
                $("#Inverter_Enabled_modal").val(rel.data.enabled);
                if (rel.data.warrantyDate != "0001-01-01") {
                    $("#Inverter_WarrantyDate_modal").val(rel.data.warrantyDate);
                } else {
                    $("#Inverter_WarrantyDate_modal").val(null);
                }




                $("#Inverter-modal").modal();
            }, 'json');

        });
        //#endregion

        //#region 刪除裝置
        $('#Device_table').on("click", "button.del-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');
            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/PowerStation/DeleteOneDevice/";
                        var send_data = {
                            SelectedId: selected_id,
                            PowerStationId: stationId
                        }
                        $.post(url, send_data, function (rel) {
                            if (rel.code != "0000") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            DeviceTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 新增異常設定資料
        function AddException() {
            selected_id = 0;
            $("#Exception-modal .modal-title").html("異常設定資料 - 新增");
            urlApicallItem();
            $("#Exception-form").trigger("reset");
            $("#Exception-modal").modal();
        }
        //#endregion

        //#region 儲存異常設定資料
        function SaveException() {

            if ($("#Exception-form").valid()) {


                var url = "/PowerStation/SaveException";
                var send_data = {
                    Id: selected_id,
                    PowerStationId: stationId,
                    Type: $("#Exception_Type_modal").val(),
                    UpperLimit: ($("#Exception_UpperLimit_modal").val() != "") ? $("#Exception_UpperLimit_modal").val() : "-9999",
                    LowerLimit: ($("#Exception_LowerLimit_modal").val() != "") ? $("#Exception_LowerLimit_modal").val() : "-9999",
                    Alarm: $("#Exception_Alarm_modal").val()
                }
                $.post(url, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    else {
                        toast_ok(rel.msg);
                        $('#Exception-modal').modal('hide');
                        ExceptionTable.ajax.reload();
                        return;
                    }
                }, 'json');
            }
        }
        //#endregion

        //#region 取一筆異常設定
        $('#Exception_table').on("click", "button.edit-btn", function () {
            $("#Exception-modal .modal-title").html("異常設定資料 - 編輯");
            var tyname = $(this).parents('tr').attr('data-typename');
            selected_id = $(this).parents('tr').attr('data-id');
            //取得單一異常設定資料
            var url = "/PowerStation/GetOneException/";
            var send_data = {
                SelectedId: selected_id,
                PowerStationId: stationId,
            }
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $("#Exception_Type_modal").empty();
                $("#Exception_Type_modal").append($("<option />").val(rel.data.type).text(tyname));
                $("#Exception_Type_modal").attr('disabled', true);
                $("#Exception_Alarm_modal").val(rel.data.alarm);
                $("#Exception_UpperLimit_modal").val(rel.data.upperLimit);
                $("#Exception_LowerLimit_modal").val(rel.data.lowerLimit);

                $("#Exception-modal").modal();
            }, 'json');

        });
        //#endregion

        //#region 刪除異常
        $('#Exception_table').on("click", "button.del-btn", function () {
            selected_id = $(this).parents('tr').attr('data-id');

            Swal.fire(
                {
                    title: "刪除",
                    text: "你確定是否刪除此筆資料?",
                    type: "warning",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: "是",
                    cancelButtonText: "否"
                }).then(function (result) {
                    if (result.value) {
                        var url = "/PowerStation/DeleteOneException/";
                        var send_data = {
                            SelectedId: selected_id,
                            PowerStationId: stationId,
                        }
                        $.post(url, send_data, function (rel) {
                            if (rel.code == "9999") {
                                toast_error(rel.msg);
                                return;
                            }
                            toast_ok(rel.msg);
                            ExceptionTable.ajax.reload();
                        }, 'json');
                    }
                });

        });
        //#endregion

        //#region 上傳資料 tab

        Dropzone.autoDiscover = false;

        //#region 電站圖片 Dropzone
        var powerStationImagsDropzone = new Dropzone("#power-station-images-form", {
            url: "/PowerStation/SavePowerStationImages",
            paramName: "StationImage",
            acceptedFiles: "image/*",
            autoProcessQueue: false,
            parallelUploads: 5,
            maxFiles: 5,
            addRemoveLinks: true,
            uploadMultiple: true,
            dictRemoveFile: "移除",
            init: function (e) {

                var myDropzone = this;
                $("#upload-station-image").click(function (e) {
                    myDropzone.processQueue();
                });

                
                myDropzone.on("sendingmultiple", function (file, xhr, data) {
                    temp_count = countPowerStationImage + myDropzone.files.length;
                    if (temp_count > 5) {
                        toast_warning("圖片總數量不可超過 5 張");
                        file.forEach(function (item) {
                            myDropzone.removeFile(item);
                        });
                        return;
                    }
                    else {
                        data.append("PowerStationId", stationId);
                        file.forEach(function (item) {
                            data.append("StationImages", item);
                        });
                    }
                });

                myDropzone.on("successmultiple", function (file, rel) {
                    if (rel.code == "9999") {
                        toast_error(rel.msg);
                        return;
                    }

                    toast_ok(rel.msg);
                    countPowerStationImage = rel.data.length;
                    powerStationImagsDropzone.removeAllFiles();

                    powerStationImageCard = $("#power-station-image-card > .row");
                    powerStationImageCard.empty();
                    rel.data.forEach(function (value, index) {
                        CreatePowerStationImageBox(powerStationImageCard, value);
                    });

                });
            }
        });
        //#endregion

        //#region 創建電站圖片box
        function CreatePowerStationImageBox(dom, value) {
            var str = '<div class="col-xl" style="max-width: 20%;">' +
                '<div class="card border m-auto m-lg-0" style="padding: 9.5px;">' +
                '<img src="' + value.image + '" class="card-img-top img-zoom" alt="...">' +
                '<a href="javascript:void(0);" class="btn btn-danger btn-lg btn-icon rounded-circle waves-effect waves-themed position-absolute pos-top pos-right del-power-station-image-btn" data-id="' + value.id + '">' +
                '<i class="fal fa-times"></i>' +
                '</a>' +
                '<div class="card-body">' +
                '<div class="custom-control custom-checkbox">';
            if (value.isMainDisplay == 1) {
                str += '<input type="checkbox" class="custom-control-input ckeck-main-display" data-id="' + value.id + '" id="ckeck_main_display_' + value.id + '" checked>';
            }
            else {
                str += '<input type="checkbox" class="custom-control-input ckeck-main-display" data-id="' + value.id + '" id="ckeck_main_display_' + value.id + '">';
            }
                str += '<label class="custom-control-label" for="ckeck_main_display_' + value.id + '">卡片顯示圖</label>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';

            dom.append(str);
        }
        //#endregion

        //#region 刪除電站圖片
        $('#power-station-image-card').on("click", "a.del-power-station-image-btn", function () {

            var selectedImageId = $(this).attr("data-id");

            var div = $(this).parents(".col-xl");

            Swal.fire({
                title: "刪除",
                text: "你確定是否刪除此筆資料?",
                type: "warning",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: "是",
                cancelButtonText: "否"
            }).then(function (result) {
                if (result.value) {

                    var url = "/PowerStation/DeletePowerStationImage";

                    var send_data = {
                        SelectedId: selectedImageId,
                        PowerStationId: stationId
                    }

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

                        toast_ok(rel.msg);
                        countPowerStationImage -= 1;
                        div.remove();
                    }, 'json');
                }
            });
        });
        //#endregion

        //#region 卡片顯示圖
        $("#power-station-image-card").on("click", ".ckeck-main-display", function () {

            var selectedImageId = $(this).attr("data-id");

            $(".ckeck-main-display").each(function (index, item) {

                var currentImageId = $(item).attr("data-id");
                if (selectedImageId != currentImageId) {
                    $(item).prop('checked', false);
                }
            });

            if (!this.checked) {
                this.checked = true;
                return;
            }

            var url = "/PowerStation/ChangeMainDisplay";

            var send_data = {
                PowerStationId: stationId,
                TargetImageId: selectedImageId
            }

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

                toast_ok(rel.msg);
            }, 'json');
        });
        //#endregion

        //#region 單線圖 Dropzone
        var powerStationSingleLineDropzone = new Dropzone("#power-station-single-line-form", {
            url: "/PowerStation/SavePowerStationSingleLine",
            acceptedFiles: "image/*,application/pdf",
            autoProcessQueue: false,
            parallelUploads: 5,
            maxFiles: 5,
            addRemoveLinks: true,
            uploadMultiple: true,
            dictRemoveFile: "移除",
            init: function (e) {

                var myDropzone = this;
                $("#upload-station-single-line").click(function (e) {
                    myDropzone.processQueue();
                });

                myDropzone.on("sendingmultiple", function (file, xhr, data) {
                    temp_count = countPowerStationSingleLine + myDropzone.files.length;
                    if (temp_count > 5) {
                        toast_warning("圖片總數量不可超過 5 張");
                        file.forEach(function (item) {
                            myDropzone.removeFile(item);
                        });
                        return;
                    }
                    else {
                        data.append("PowerStationId", stationId);
                        file.forEach(function (item) {
                            data.append("SingleLineImages", item);
                        });
                    }
                });

                myDropzone.on("successmultiple", function (file, rel) {
                    if (rel.code == "9999") {
                        toast_error(rel.msg);
                        return;
                    }

                    toast_ok(rel.msg);
                    countPowerStationSingleLine = rel.data.length;
                    powerStationSingleLineDropzone.removeAllFiles();

                    powerStationSingleLineCard = $("#power-station-single-line-card > .row");
                    powerStationSingleLineCard.empty();
                    rel.data.forEach(function (value, index) {
                        var split = value.image.split(".");
                        if (split[split.length - 1].toLowerCase() == "pdf") {
                            CreatePowerStationSingleLineBoxPDF(powerStationSingleLineCard, value);
                        } else {
                            CreatePowerStationSingleLineBox(powerStationSingleLineCard, value);
                        }

                        
                    });

                });
            }
        });
        //#endregion

        //#region 創建單線圖box
        function CreatePowerStationSingleLineBox(dom, value) {
            var str = '<div class="col-xl" style="max-width: 20%;">' +
                '<div class="card border m-auto m-lg-0" style="padding: 9.5px;">' +
                '<img src="' + value.image + '" class="card-img-top img-zoom" alt="...">' +
                '<a href="javascript:void(0);" class="btn btn-danger btn-lg btn-icon rounded-circle waves-effect waves-themed position-absolute pos-top pos-right del-power-station-single-line-btn" data-id="' + value.id + '">' +
                '<i class="fal fa-times"></i>' +
                '</a>' +
                '</div>' +
                '</div>';

            dom.append(str);
        }
        //#endregion

        //#region 創建單線圖PDFbox
        function CreatePowerStationSingleLineBoxPDF(dom, value) {
            var str = '<div class="col-xl" style="max-width: 20%;">' +
                '<div class="card border m-auto m-lg-0" style="padding: 9.5px;">' +
                '<a href="' + value.image + '" download>' +
                '<img src="/img/pdf.png" class="card-img-top " alt="...">' +
                '</a>'+
                '<a href="javascript:void(0);" class="btn btn-danger btn-lg btn-icon rounded-circle waves-effect waves-themed position-absolute pos-top pos-right del-power-station-single-line-btn" data-id="' + value.id + '">' +
                '<i class="fal fa-times"></i>' +
                '</a>' +
                '</div>' +
                '</div>';

            dom.append(str);
        }
        //#endregion


        //#region 刪除單線圖
        $('#power-station-single-line-card').on("click", "a.del-power-station-single-line-btn", function () {

            var selectedImageId = $(this).attr("data-id");

            var div = $(this).parents(".col-xl");

            Swal.fire({
                title: "刪除",
                text: "你確定是否刪除此筆資料?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: "是",
                cancelButtonText: "否"
            }).then(function (result) {
                if (result.value) {

                    var url = "/PowerStation/DeletePowerStationSingleLine";

                    var send_data = {
                        SelectedId: selectedImageId,
                        PowerStationId: stationId
                    }

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

                        toast_ok(rel.msg);
                        countPowerStationSingleLine -= 1;
                        div.remove();
                    }, 'json');
                }
            });
        });
        //#endregion

        //#endregion

        //$('#Exception_UpperLimit_modal').change(function () {
        //    upper = $('#Exception_UpperLimit_modal').val();
        //    $("#Exception_LowerLimit_modal").rules("remove");
        //    $("#Exception_LowerLimit_modal").rules("add", {
        //        required: true,
        //        max: Number(upper),
        //        min: 0
        //    });
        //});

        function padLeft(str, lenght) {
            if (str.length >= lenght)
                return str;
            else
                return padLeft("0" + str, lenght);
        }
        $("#Device-form").validate({
            rules: {
                Device_Brand_modal: {
                    required: true
                },
                Device_Name_modal: {
                    required: true
                },
                Device_ProductModel_modal: {
                    required: true
                },
                Device_InstallDate_modal: {
                    required: true
                },
                Device_ColName_modal: {
                    max: 50,
                    min: 1
                }
            }
        });

        $("#station-created-form").validate({
            rules: {
                address_detail: {
                    required: true
                },
                power_station_name: {
                    required: true
                },
                coordinate: {
                    required: true
                },
                estimate_efficacy:
                {
                    required: true
                },
                estimate_kwh:
                {
                    required: true
                },
                estimated_recovery_time:
                {
                    required: true
                },
                generating_capacity:
                {
                    required: true
                }
            }
        });

        $('#power_station_operation_personnel').change(function () {
            if (stationId == 'new' || station_infocreate) {
                if ($('#power_station_operation_personnel').val().length == 0) {
                    $('#power_station_operation_personnel-error').show();
                } else {
                    $('#power_station_operation_personnel-error').hide();
                }
            }
        });

        $('#coordinate').change(function () {
            var a = $('#coordinate').val().split(',');
            if (stationId == 'new' || station_infocreate) {
                if (a.length != 2) {
                    $('#coordinate_text-error').show();
                } else {
                    $('#coordinate_text-error').hide();
                }
            }
        });



        $("#Inverter-form").validate({
            rules: {
                Inverter_ControllerId_modal: {
                    required: true
                },
                Inverter_InverterName_modal: {
                    required: true
                },
                Inverter_InstallDate_modal: {
                    required: true
                },
                Inverter_Brand_modal: {
                    required: true
                },
                Inverter_Model_modal: {
                    required: true
                },
                Inverter_Capacity_modal: {
                    required: true
                },
            }
        });


        $("#Operation-form").validate({
            rules: {
                Operation_factory_modal: {
                    required: true
                },
                Operation_name_modal: {
                    required: true
                },
                Operation_phone_modal: {
                    required: true
                },
                Operation_email_modal: {
                    required: true
                },
                Operation_role_modal: {
                    required: true
                },
                Operation_taxIDNumber_modal: {
                    required: true,
                    maxlength: 8
                },
                Operation_remark_modal: {
                    maxlength: 255
                }
            }
        });


        $("#ShareDevice-form").validate({
            rules: {
                ShareDevice_PowerStationId_modal: {
                    required: true
                },
                ShareDevice_UID_modal: {
                    required: true
                }
            }
        });


        function urlApicallItem()
        {
            var urlApicallItem = "/PowerStation/GetApicallItemList";
            var send_data = {
                powerStationId: stationId
            }
            $.post(urlApicallItem, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $("#Exception_Type_modal").empty();

                if (rel.data.length > 0) {
                    $.each(rel.data, function (index, val) {
                        $("#Exception_Type_modal").append($("<option />").val(val.value).text(val.text));
                    });
                    $("#Exception_Type_modal").attr('disabled', false);
                    $("#savebtn").attr('disabled', false);
                }
                else {
                    $("#Exception_Type_modal").append($("<option />").val(0).text('無異常設定可新增'));
                    $("#Exception_Type_modal").attr('disabled', true);
                    $("#savebtn").attr('disabled', true);
                }

            });
        }




    </script>
}