@{
    ViewData["MainNum"] = "6";
    ViewData["SubNum"] = "3";
    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 active">運維作業記錄</li>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>
<div class="subheader">
    <h1 class="subheader-title">
        <i class="subheader-icon fal fa-globe"></i> 運維作業記錄
    </h1>
</div>

<!-- Your main content goes below here: -->
<div id="panel-5" class="panel">
    <div class="panel-container show">
        <div class="panel-content">
            <div class="row mb-3 d-flex justify-content-start px-3">
                <div class="pr-3">
                    <div class="btn-group btn-group-md">
                        <button type="button" class="btn btn-success waves-effect waves-themed status-type" onclick="CheckStatus(0,this)">未完成</button>
                        <button type="button" class="btn btn-secondary waves-effect waves-themed status-type" onclick="CheckStatus(1,this)">完成</button>
                        <button type="button" class="btn btn-secondary waves-effect waves-themed status-type" onclick="CheckStatus(2,this)">刪除區</button>
                    </div>
                </div>
                <div class="pr-3">
                    <div class="btn-group btn-group-md">
                        <button type="button" class="btn btn-success waves-effect waves-themed" onclick="ChangeType(0)" id="button0">全部</button>
                        <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="ChangeType(3)" id="button3">維修</button>
                        <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="ChangeType(2)" id="button2">巡檢</button>
                        <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="ChangeType(1)" id="button1">清洗</button>
                    </div>
                </div>
                <div class="pr-3">
                    <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="ChangeDate30()">近30天</button>
                </div>
                <div class="pr-3">
                    <div class="form-group">
                        <input class="form-control" id="date-range" type="text" name="date" value="">
                    </div>
                </div>
                <div class="pr-5">
                    <div class="form-group">
                        <input class="form-control" id="FormNum" type="text" value="" placeholder="表單號">
                    </div>
                </div>
                <div class="pr-3">
                    <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="Search()">表單號查詢</button>
                </div>
            </div>
            <div class="row mb-3 d-flex align-items-center px-3">
                <div class="pr-3">
                    <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="Allcity()" id="Allcity">全部縣市</button>
                </div>
                <div class="pr-3">
                    <div class="frame-wrap" id="city">
                    </div>
                </div>
            </div>

            <div class="row mb-5 d-flex align-items-top px-3">
                <div class="col-1 p-0">
                    <button type="button" class="btn btn-secondary waves-effect waves-themed" onclick="Allpowerstation()">全選</button>
                </div>
                <div class="col-11">
                    <div class="row frame-wrap" id="CheckPowerStation">

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

            <div class="row d-flex justify-content-end px-3">
                <button type="button" class="btn btn-info waves-effect waves-themed mb-3 mr-2" onclick="ExportExcel()">
                    <span class="fal fa-file-excel mr-1"></span>
                    匯出
                </button>
                <a href="javascript:;" class="btn btn-success waves-effect waves-themed mb-3 mr-2" onclick="AddRecord()">
                    <span class="fal fa-plus mr-1"></span>
                    維修單
                </a>
            </div>
            <div class="frame-wrap">
                <table id="operation_record_table" class="table table-bordered table-hover m-0 text-center">
                    <thead class="thead-themed">
                        <tr>
                            <th>電廠</th>
                            <th>表單號</th>
                            <th>項目</th>
                            <th>維修項目</th>
                            <th>狀態</th>
                            <th>執行人員</th>
                            <th>本次作業預計</th>
                            <th>檔案</th>
                            <th>完成時間</th>
                            <th>創建時間</th>
                            <th>刪除時間</th>
                            @if (ViewBag.myUser.Role.Layer != (int)RoleLayerEnum.CompanyUser)
                            {
                                <th>功能</th>
                            }
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>

                <table id="NoView" style="display:none">
                    <thead class="thead-themed">
                        <tr>
                            <th>電廠</th>
                            <th>表單號</th>
                            <th>項目</th>
                            <th>維修項目</th>
                            <th>狀態</th>
                            <th>執行人員</th>
                            <th>本次作業預計</th>
                            <th>檔案</th>
                            <th>完成時間</th>
                        </tr>
                    </thead>
                    <tbody id="NoViewbody">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="record-form-modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    <span class="main-title"></span><span class="sub-title"></span>
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <form id="record-form">
                    <div class="row mb-3">
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label class="form-label" for="power_station_select_modal"><span class="text-danger">*</span>電站</label>
                                <select class="form-control" id="power_station_select_modal">
                                </select>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label class="form-label" for="work_time_modal"><span class="text-danger">*</span>作業日期</label>
                                <input class="form-control" id="work_time_modal" type="date" name="work_time_modal" />
                                <label id="work_time_modal-error" class="" style="z-index:1;color:red;display:none">此為必填欄位</label>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label class="form-label" for="example-select"><span class="text-danger">*</span>狀態</label>
                                <div>
                                    <div class="custom-control custom-radio custom-control-inline">
                                        <input type="radio" class="custom-control-input ml-auto" id="status_none_complete" name="status_modal" value="0" />
                                        <label class="custom-control-label" for="status_none_complete">未完成</label>
                                    </div>
                                    <div class="custom-control custom-radio custom-control-inline">
                                        <input type="radio" class="custom-control-input ml-auto" id="status_complete" name="status_modal" value="1" />
                                        <label class="custom-control-label" for="status_complete">完成</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="">
                                <label class="form-label" for="work_person_select_modal"><span class="text-danger">*</span>執行人員</label>
                                <select class="form-control" id="work_person_select_modal" multiple="multiple">
                                </select>
                                <label id="work_person_select_modal-error" class="" style="z-index:1;color:red;display:none">此為必填欄位</label>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3 fix-div">
                        <div class="col-lg-6">
                            <div class="form-group">
                                <div class="form-group">
                                    <label class="form-label" for="error_code_modal">異常編號</label>
                                    <input class="form-control" id="error_code_modal" type="text" name="error_code_modal" disabled />
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label class="form-label" for="fix_do_modal">維修項目</label>
                                <input class="form-control" id="fix_do_modal" type="text" name="fix_do_modal" />
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-lg-6">
                            <div class="form-group">
                                <label class="form-label" for="fix_firm_modal">負責廠商</label>
                                <select class="form-control" id="fix_firm_select_modal"></select>
                            </div>
                        </div>
                        <div class="col-lg-6 mt-5">
                            <div class="custom-control custom-checkbox d-flex align-content-center">
                                <input type="checkbox" class="custom-control-input" id="EmailcheckBox">
                                <label class="custom-control-label" for="EmailcheckBox">發送Email通知</label>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-lg-12">
                            <div class="form-group">
                                <label class="form-label" for="notice_textarea_modal">項目內容</label>
                                <textarea class="form-control" id="notice_textarea_modal" rows="5"></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-lg-12">
                            <div class="form-group">
                                <label class="form-label" for="description_textarea_modal">結果描述</label>
                                <textarea class="form-control" id="description_textarea_modal" rows="5"></textarea>
                            </div>
                        </div>
                    </div>
                </form>
                <div class="row align-items-center">
                    <div class="col-2">
                        <p>檔案上傳</p>
                    </div>
                    <div id="record_files_div" class="col-10">
                        <div class="row px-3 mb-3 d-flex justify-content-start align-items-center img-zoom-div">

                        </div>
                    </div>
                </div>
                <div class="row px-3">
                    <form id="record-file-form" class="dropzone needsclick dz-clickable col-12" style="min-height: 7rem;">
                        @*<div class="fallback">
                                <input type="file" multiple />
                            </div>*@
                        <div class="dz-message needsclick">
                            <i class="fal fa-cloud-upload text-muted mb-3"></i> <br>
                            <span class="text-uppercase">將圖片拖曳至這裡或點擊選擇圖片.</span>
                            <br>
                            <span class="fs-sm text-muted">僅供預覽，並未實際上傳。</span>
                        </div>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="save-record-btn" onclick="SaveRecord()">確定</button>
            </div>
        </div>
    </div>
</div>

@section Scripts{
    <script>
        var operationRecordTable;
        var selected_id = 0; var selected_work_type = -1;
        var record;
        var countOperationRecordFile = 0;
        var recordFileDropzone;
        var ids = new Array(0);//當前選擇縣市
        var powerids = new Array(0);//當前選擇電站
        var Allids = new Array(0);//全部縣市
        var Allpowerids = new Array(0);//全部電站
        var Type = 0; // 項目
        var datepicker;
        var AllpoweridsType = true;
        var AllidsType = true;
        var status = 0; //1:完成 0:未完成
        var Searchtype = false;
        var Deleteshow = false;

        //#region Array.Remove
        Array.prototype.remove = function (val) {
            var index = this.indexOf(val);
            if (index > -1) {
                this.splice(index, 1);
            }
        };
        //#endregion

        $(function () {
            //#region Date-Picker

            datepicker = $('#date-range').daterangepicker({
                autoUpdateInput: false,
                locale: { format: 'YYYY/MM/DD' },
                opens: 'left'
            }, function (start, end, label) {
                @*console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));*@
            });

            $('#date-range').on('apply.daterangepicker', function (ev, picker) {
                $(this).val(picker.startDate.format('YYYY/MM/DD') + ' - ' + picker.endDate.format('YYYY/MM/DD'));
                $(this).trigger('change');
            });

            $('#date-range').on('cancel.daterangepicker', function (ev, picker) {
                $(this).val('');
                $(this).trigger('change');
            });

            //#endregion

            //#region 預設載入該使用者可以選擇的電站
            var city_url = "/Operation/GetMyCities";
            $.post(city_url, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

                $('#city').empty();
                for (var i = 0; i < rel.data.length; i++) {
                    $('#city').append("<button type='button' class='btn btn-success waves-effect waves-themed ml-2' id='" + 'cityID_' + rel.data[i].cityId + "'>" +
                        rel.data[i].cityName +
                        "<span class= 'badge bg-success-700 ml-2' >" + rel.data[i].amount + "</span >" +
                        "</button >");
                    ids.push(rel.data[i].cityId);
                    Allids.push(rel.data[i].cityId);
                }

                var send_data = {
                    cityIds: ids
                }
                var Nurl = "/Operation/GetPowerStationByFilter";
                $.post(Nurl, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }

                    //modal 電站 下拉式選單
                    $("#power_station_select_modal").empty();
                    $.each(rel.data, function (index, val) {
                        $("#power_station_select_modal").append($("<option />").val(val.id).text(val.name));
                    });

                    //預設查詢第一個
                    $("#power_station_select_modal").val($("#power_station_select_modal option:first").val()).trigger('change');
                })


                $('#Allcity').trigger("click");

                getPowerStationCheckBox();
            }, 'json');


            @*var Nurl = "/PowerStation/GetSolarCitySummary";
            $.post(Nurl, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                for (var i = 0; i < rel.data.length; i++) {
                    $('#city').append("<button type='button' class='btn btn-success waves-effect waves-themed ml-2' id='" + 'cityID_' + rel.data[i].cityId + "'>" +
                        rel.data[i].city +
                        "<span class= 'badge bg-success-700 ml-2' >" + rel.data[i].amount + "</span >" +
                        "</button >");
                    ids.push(String(rel.data[i].cityId));
                    Allids.push(String(rel.data[i].cityId));
                }

                var send_data = {
                    cityid: ids
                }
                ids.sort();

                var Nurl = "/PowerStation/GetSolarByCity";
                $.post(Nurl, send_data, function (rel) {
                    if (rel.code != "0000") {
                        toast_error(rel.msg);
                        return;
                    }
                    $('#CheckPowerStation').empty();
                    $.each(rel.data, function (index, val) {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' ></div>");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' id='check_" + val.id + "' checked>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                        powerids.push(String(val.id));
                        Allpowerids.push(String(val.id));
                    });

                    //modal 電站 下拉式選單
                    $("#power_station_select_modal").empty();
                    $.each(rel.data, function (index, val) {
                        $("#power_station_select_modal").append($("<option />").val(val.id).text(val.name));
                    });

                    //預設查詢第一個
                    $("#power_station_select_modal").val($("#power_station_select_modal option:first").val()).trigger('change');

                    $('#Allcity').trigger("click");
                    if (status == 2) {
                        operationRecordTable.column(10).visible(true);
                    }
                    else {
                        operationRecordTable.column(10).visible(false);
                    }
                    operationRecordTable.ajax.reload();

                })
            })*@
            //#endregion

            //#region 切換電站時，載入該電站運維人員
            $("#power_station_select_modal").change(function () {

                //查詢該電站的運維人員
                var url_power_station_operation_personnel = "/PowerStation/GetOperationPersonnelSelectOptionList";

                send_data = {
                    PowerStationId: $(this).val()
                }

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

                    $("#work_person_select_modal").empty();
                    if (rel.data.length > 0) {

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

                        if (record != null || record != undefined) {
                            $("#work_person_select_modal").val(record.workPersonIds);
                        }
                    }

                    $("#work_person_select_modal").select2({ dropdownParent: $('#record-form-modal') });


                });

                //查詢該電站的廠商
                var url_power_station_firm = "/PowerStation/GetFirmSelectOptionList";

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

                    $("#fix_firm_select_modal").empty();
                    if (rel.data.length > 0) {

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

                    $("#fix_firm_select_modal").val($("#fix_firm_select_modal option:first").val()).trigger('change');

                    if (record != undefined && record != null) {
                        $("#fix_firm_select_modal").val(record.fixFirm)
                    }
                });
            });
            //#endregion

            //#region 運維作業記錄 DataTable
            operationRecordTable = $("#operation_record_table").DataTable({
                "pageLength": 20,
                "paging": true,
                "lengthChange": false,
                "searching": false,
                "ordering": false,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                "order": [[10, "desc"]],
                "columns": [{
                    "data": "powerStationName"
                }, {
                    "data": "formId"
                }, {
                    "data": "workTypeText"
                }, {
                    "data": "fixDo"
                }, {
                    "data": "statusText"
                }, {
                    "data": "workPersonName"
                }, {
                    "data": "operationPredict"
                }, {
                    "data": "recordFiles"
                }, {
                    "data": "finishTime"
                },{
                    "data": "createdAt"
                }, {
                    "data": "updatedAt",
                    //"defaultContent": '<button class="btn btn-danger del-btn">刪除</button>'
                }, {
                    "data": "function"
                }],
                "columnDefs": [{
                    'targets': 7,
                    'searchable': false,
                    'orderable': false,
                    'className': 'dt-body-center img-zoom-div',
                    'createdCell': function (td, cellData, rowData, row, col) {
                        $(td).empty();
                        $(td).append('<div class="row"></div>');

                        if (cellData != null) {
                            cellData.forEach(function (value, index) {
                                CreateRecordFileBox($(td).children(".row"), value, false);
                            });
                        }
                    }
                }, {
                    'targets': 9,
                    'visible': @(ViewBag.myUser.Role.Layer == (int)RoleLayerEnum.CompanyUser ? "false" : "true")
                }],
                "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-work-type', data.workType);
                },
                "ajax": {
                    "url": "/Operation/OperationRecordList",
                    "type": "POST",
                    "data": function (d) {
                        d.PowerStationIds = powerids;
                        d.WorkType = Type;
                        d.Range = $('#date-range').val();
                        d.status = status;
                    },
                    "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 = [];
                        }
                        var realdata;
                        if (Searchtype) {
                            realdata = new Array(0);
                            $.each(this.data, function (index, val) {
                                var num = $('#FormNum').val();
                                if (val.formId == ("<a href='javascript:;' class='waves-effect waves-themed mb-3 mr-2 edit-btn'>" + num + "</a>")) {
                                    realdata.push(val);
                                }
                            });
                            Searchtype = false;
                        } else {
                            realdata = this.data;
                        }
                        return realdata;
                    }
                },
                "error": function (xhr, error, thrown) {
                    console.log(xhr);
                }
            });
            //#endregion
        });

        $('#work_person_select_modal').change(function () {
            if ($('#work_person_select_modal').val().length == 0) {
                $('#work_person_select_modal-error').show();
            } else {
                $('#work_person_select_modal-error').hide();
            }
        });

        $('#work_time_modal').change(function () {
            $("#work_time_modal-error").hide();
        });



        function getPowerStationCheckBox() {
            var send_data = {
                cityIds: ids
            }

            var Nurl = "/Operation/GetPowerStationByFilter";
            $.post(Nurl, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $('#CheckPowerStation').empty();
                powerids = [];
                $.each(rel.data, function (index, val) {

                    if ($.inArray(parseInt(val.cityId), ids) > -1) {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' name='check_power_station[]' id='check_" + val.id + "' value='" + val.id + "' checked>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                        powerids.push(String(val.id));
                    } else {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' name='check_power_station[]' id='check_" + val.id + "' value='" + val.id + "' >");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");

                        if ($.inArray(parseInt(val.id), powerids) > -1) {
                            powerids.splice($.inArray(parseInt(val.id), powerids), 1);
                        }
                    }
                    Allpowerids.push(String(val.id));
                });

                if (status == 2) {
                    operationRecordTable.column(10).visible(true);
                }
                else {
                    operationRecordTable.column(10).visible(false);
                }
                operationRecordTable.ajax.reload();
            })
        }

        //#region 改變項目
        function ChangeType(type)
        {
            Type = type;
            for (var i = 0; i < 4; i++)
            {
                var name = "button" + i;
                document.getElementById(name).setAttribute("class", "btn btn-secondary waves-effect waves-themed");
            }
            document.getElementById("button" + type).setAttribute("class", "btn btn-success waves-effect waves-themed");
            if (status == 2) {
                operationRecordTable.column(10).visible(true);
            }
            else {
                operationRecordTable.column(10).visible(false);
            }
            operationRecordTable.ajax.reload();

        }
        //#endregion

        //#region 改變日期
        $('#date-range').on('change', function () {
            if (status == 2) {
                operationRecordTable.column(10).visible(true);
            }
            else {
                operationRecordTable.column(10).visible(false);
            }
            operationRecordTable.ajax.reload();
        });
        //#endregion

        //#region 新增維修單
        function AddRecord() {
            selected_id = 0;
            selected_work_type = 2;
            record = undefined;
            $("#record-form-modal .modal-title .main-title").html("維修單");
            $("#record-form-modal .modal-title .sub-title").html("");
            $("#power_station_select_modal").attr("disabled", false);
            $("#power_station_select_modal").val($("#power_station_select_modal option:first").val()).trigger('change');
            $(".fix-div").show();
            $("#record-form").trigger("reset");
            $("input[name=status_modal][value='" + 0 + "']").prop('checked', true); //狀態
            $("#record_files_div > .row").empty();

            $('#work_person_select_modal-error').hide();
            $("#work_time_modal-error").hide();


            $("#EmailcheckBox").prop("checked", false);
            $("#record-form-modal").modal();
        }
        //#endregion

        //#region 縣市全選
        function Allcity() {
            var Newpowerids = new Array(0);
            ids = [];
            $.each(Allids, function (index, val) {
                var cityid = 'cityID_' + val;
                if (AllidsType) {
                    document.getElementById(cityid).setAttribute("class", 'btn btn-outline-success waves-effect waves-themed ml-2');
                    ids = [];
                    powerids = [];
                }
                else {
                    document.getElementById(cityid).setAttribute("class", 'btn btn-success waves-effect waves-themed ml-2');
                    ids.push(val);
                }
            });
            if (AllidsType) {
                AllidsType = false;
                AllpoweridsType = false;
            } else {
                AllidsType = true;
            }

            getPowerStationCheckBox();

            @*var send_data = {
                cityid: ids
            }
            var Nurl = "/PowerStation/GetSolarByCity";
            $.post(Nurl, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $('#CheckPowerStation').empty();
                Allpowerids = [];
                $.each(rel.data, function (index, val) {
                    if (powerids.includes(String(val.id))) {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' id='check_" + val.id + "' checked>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                        Newpowerids.push(String(val.id));
                    }
                    else {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' id='check_" + val.id + "'>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                    }
                    Allpowerids.push(String(val.id));
                });
                powerids = [];
                powerids = Newpowerids;
            })
            if (status == 2) {
                operationRecordTable.column(10).visible(true);
            }
            else {
                operationRecordTable.column(10).visible(false);
            }
            operationRecordTable.ajax.reload();*@
        }

        function Allcity2() {
            var Newpowerids = new Array(0);
            ids = [];
            $.each(Allids, function (index, val) {
                var cityid = 'cityID_' + val;
                if (AllidsType) {
                    document.getElementById(cityid).setAttribute("class", 'btn btn-outline-success waves-effect waves-themed ml-2');
                    ids = [];
                    powerids = [];
                }
                else {
                    document.getElementById(cityid).setAttribute("class", 'btn btn-success waves-effect waves-themed ml-2');
                    ids.push(val);

                }
            });
            if (AllidsType) {
                AllidsType = false;
                AllpoweridsType = false;
            } else {
                AllidsType = true;
            }

            getPowerStationCheckBox()

            @*var send_data = {
                cityid: ids
            }
            var Nurl = "/PowerStation/GetSolarByCity";
            $.post(Nurl, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $('#CheckPowerStation').empty();
                Allpowerids = [];
                $.each(rel.data, function (index, val) {
                    if (powerids.includes(String(val.id))) {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' id='check_" + val.id + "' checked>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                        Newpowerids.push(String(val.id));
                    }
                    else {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' id='check_" + val.id + "'>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                    }
                    Allpowerids.push(String(val.id));
                });
                powerids = [];
                powerids = Newpowerids;


                if (AllpoweridsType) {
                    AllpoweridsType = false;
                } else {
                    AllpoweridsType = true;
                }

                powerids = [];
                $.each(Allpowerids, function (index, val) {
                    if (AllpoweridsType) {
                        $('#check_' + val).prop("checked", true);
                        powerids.push(val);
                    } else {
                        $('#check_' + val).prop("checked", false);
                        powerids = [];
                    }
                })
                if (status == 2) {
                    operationRecordTable.column(10).visible(true);
                }
                else {
                    operationRecordTable.column(10).visible(false);
                }
                operationRecordTable.ajax.reload();
            })*@
        }
        //#endregion

        //#region 電站全選
        function Allpowerstation() {
            if (AllpoweridsType) {
                AllpoweridsType = false;
            } else {
                AllpoweridsType = true;
            }

            powerids = [];
            $('input[name="check_power_station[]"]').map(function () {
                if (AllpoweridsType) {
                    $(this).prop("checked", true);
                    powerids.push($(this).val());
                }
                else {
                    $(this).prop("checked", false);
                }
            });
            if (status == 2) {
                operationRecordTable.column(10).visible(true);
            }
            else {
                operationRecordTable.column(10).visible(false);
            }
            operationRecordTable.ajax.reload();
        }
        //#endregion

        //#region 選擇縣市
        $('#city').on("click", "button", function () {
            var clickid = $(this).attr('id');
            var classid = clickid.split("_");
            var Newpowerids = new Array(0);
            var value = document.getElementById(clickid).className;

            if (value == 'btn btn-outline-success waves-effect waves-themed ml-2') {  //選擇
                document.getElementById(clickid).setAttribute("class", 'btn btn-success waves-effect waves-themed ml-2');
                if ($.inArray(parseInt(classid[1]), ids) < 0) {
                    ids.push(parseInt(classid[1]));
                }
            }
            else { //取消
                document.getElementById(clickid).setAttribute("class", 'btn btn-outline-success waves-effect waves-themed ml-2');
                if ($.inArray(parseInt(classid[1]), ids) > -1) {
                    ids.splice($.inArray(parseInt(classid[1]), ids), 1);
                }
            }

            getPowerStationCheckBox();
            @*ids.sort();
            var Nurl = "/PowerStation/GetSolarByCity";
            $.post(Nurl, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $('#CheckPowerStation').empty();
                Allpowerids = [];
                $.each(rel.data, function (index, val) {
                    if (powerids.includes(String(val.id))) {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' id='check_" + val.id + "' checked>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                        Newpowerids.push(String(val.id));
                    }
                    else {
                        $('#CheckPowerStation').append("<div class='col-2 mb-2 custom-control custom-checkbox custom-control-inline' id='station_" + val.id + "' > ");
                        $('#station_' + val.id).append("<input type='checkbox' class='custom-control-input' id='check_" + val.id + "'>");
                        $('#station_' + val.id).append("<label class='custom-control-label' for='check_" + val.id + "'>" + val.name + "</label>");
                    }
                    Allpowerids.push(String(val.id));
                });
                powerids = [];
                powerids = Newpowerids;
            })
            if (status == 2) {
                operationRecordTable.column(10).visible(true);
            }
            else {
                operationRecordTable.column(10).visible(false);
            }
            operationRecordTable.ajax.reload();*@
        })
        //#endregion

        //#region 選擇電站checkbox
        $('#CheckPowerStation').on("click", "input", function () {
            var clickid = $(this).attr('id');
            var classid = clickid.split("_");
            var job = document.getElementById(clickid);
            if (job.checked == true) {
                powerids.push(classid[1]);
            }
            else {
                powerids.splice($.inArray(classid[1], powerids), 1);
            }
            if (status == 2) {
                operationRecordTable.column(10).visible(true);
            }
            else {
                operationRecordTable.column(10).visible(false);
            }
            operationRecordTable.ajax.reload();
        })

        //#endregion

        //#region 點擊圖片放大
        $('#operation_record_table').on("click", "img.img-zoom", function () {
            var _this = $(this);//將當前的pimg元素作為_this傳入函式
            imgShow("#img-zoom-outer-div", "#innerdiv", "#bigimg", _this);
        });
        //#endregion

        //#region 編輯表單內容
        $('#operation_record_table').on("click", "a.edit-btn", function () {

            work_type = $(this).parents('tr').attr('data-work-type');

            if (work_type == 0) {
                $("#record-form-modal .modal-title .main-title").html("清洗單 - ");
            } else if (work_type == 1) {
                $("#record-form-modal .modal-title .main-title").html("巡檢單 - ");
            } else {
                $("#record-form-modal .modal-title .main-title").html("維修單 - ");
            }

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

            //取得單一記錄表單
            var url = "/Operation/GetOneOperationRecord/";

            var send_data = {
                id: selected_id
            }

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

                record = rel.data;

                countOperationRecordFile = record.recordFiles.length;

                $("#record-form-modal .modal-title .sub-title").html(record.powerStationName);

                $("#power_station_select_modal").val(record.powerStationId).trigger('change');
                $("#power_station_select_modal").attr("disabled", true);

                $("#work_time_modal").val(record.workTime);
                var status = -1;
                if (record.status == 0 || record.status == 2) {
                    status = 0;
                } else if (record.status == 1 || record.status == 3) {
                    status = 1;
                }
                $("input[name=status_modal][value='" + status + "']").prop('checked', true); //狀態
                $('#work_person_select_modal').val(record.workPersonIds).trigger("change");

                selected_work_type = work_type;
                if (work_type != 2) {
                    $(".fix-div").hide();
                } else {
                    $(".fix-div").show();
                    $("#error_code_modal").val(record.errorCode);
                    $("#fix_do_modal").val(record.fixDo);
                }
                $("#fix_firm_select_modal").val(record.fixFirm).trigger("change");
                $("#notice_textarea_modal").val(record.notice);
                $("#description_textarea_modal").val(record.description);

                var str = "";

                RecordFileBox = $("#record_files_div > .row");
                RecordFileBox.empty();
                record.recordFiles.forEach(function (value, index) {
                    CreateRecordFileBox(RecordFileBox, value, true);
                });



                $("#EmailcheckBox").prop("checked", false);
                $("#record-form-modal").modal();
            }, 'json');
        });
        //#endregion

        //#region 表單驗證
        $("#record-form").validate({
            rules: {
                work_time_modal: {
                    required: true
                }
            },
        });
        //#endregion

        //#region 儲存表單資料
        function SaveRecord() {
            if ($('#work_person_select_modal').val().length > 0 && $("#work_time_modal").val() != "") {
                if ($("#record-form").valid())
                {
                    var url = "/Operation/SaveOperationRecord";

                    var formData = new FormData();

                    @*var work_person_ids = $.map($("#work_person_select_modal").val(), function (item) {
                        return parseInt(item);
                    }) *@

                    formData.append("Id", selected_id);
                    formData.append("PowerStationId", $("#power_station_select_modal").val());
                    formData.append("WorkType", selected_work_type);
                    formData.append("ErrorCode", $("#error_code_modal").val());
                    formData.append("FixDo", $("#fix_do_modal").val());
                    formData.append("FixFirm", $("#fix_firm_select_modal").val());
                    formData.append("Status", $("input[name=status_modal]:checked").val());
                    $("#work_person_select_modal").val().forEach(function (item) {
                        formData.append("WorkPersonIds", parseInt(item));
                    });
                    formData.append("WorkTime", $("#work_time_modal").val());
                    formData.append("Notice", $("#notice_textarea_modal").val());
                    formData.append("Description", $("#description_textarea_modal").val());
                    if (document.querySelector('[id=EmailcheckBox]:checked')) {
                        formData.append("Emailcheck", 1);
                    }
                    else {
                        formData.append("Emailcheck", 0);
                    }
                    $.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;
                            }

                            var myDropzone = Dropzone.forElement("#record-file-form");

                            if (myDropzone.files.length > 0) {

                                selected_id = rel.data;

                                myDropzone.processQueue();

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

                                    toast_ok(rel.msg);
                                    $('#record-form-modal').modal('hide');
                                    recordFileDropzone.removeAllFiles();
                                    if (status == 2) {
                                        operationRecordTable.column(10).visible(true);
                                    }
                                    else {
                                        operationRecordTable.column(10).visible(false);
                                    }
                                    operationRecordTable.ajax.reload();
                                });
                            } else {
                                $('#record-form-modal').modal('hide');
                                myDropzone.removeAllFiles();
                                if (status == 2) {
                                    operationRecordTable.column(10).visible(true);
                                }
                                else {
                                    operationRecordTable.column(10).visible(false);
                                }
                                operationRecordTable.ajax.reload();
                            }
                        }
                    });
                }
            }
            else
            {
                if ($('#work_person_select_modal').val().length == 0)
                {
                    $('#work_person_select_modal-error').show();
                }
                if ($("#work_time_modal").val() == "")
                {
                    $("#work_time_modal-error").show();
                }
                
            }
        }
        //#endregion

        //#region 刪除運維紀錄
        $('#operation_record_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 = "/Operation/DeleteOneOperationRecord/";
                        var send_data = {
                            Id: selected_id
                        }
                        $.post(url, send_data, function (rel) {
                            if (rel.code == "9999") {
                                toast_error(rel.msg);
                                return;
                            }
                            else if (rel.code == "9998") {
                                toast_error(rel.msg);
                                return;
                            }

                            toast_ok(rel.msg);
                            if (status == 2) {
                                operationRecordTable.column(10).visible(true);
                            }
                            else {
                                operationRecordTable.column(10).visible(false);
                            }
                            operationRecordTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 還原運維紀錄
        $('#operation_record_table').on("click", "button.redu-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 = "/Operation/ReductionOneOperationRecord/";
                        var send_data = {
                            Id: selected_id
                        }
                        $.post(url, send_data, function (rel) {
                            if (rel.code == "9999") {
                                toast_error(rel.msg);
                                return;
                            }
                            else if (rel.code == "9998") {
                                toast_error(rel.msg);
                                return;
                            }

                            toast_ok(rel.msg);
                            if (status == 2) {
                                operationRecordTable.column(10).visible(true);
                            }
                            else {
                                operationRecordTable.column(10).visible(false);
                            }
                            operationRecordTable.ajax.reload();
                        }, 'json');
                    }
                });
        });
        //#endregion

        //#region 取得電站選單資料 (未使用)
        function GetPowerStation() {
            var url_power_station_select_option = "/Operation/GetPowerStationSelectOption";
            $.get(url_power_station_select_option, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }

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

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

                //預設查詢第一個
                $("#power_station_select_modal").val($("#power_station_select_modal option:first").val()).trigger('change');
            });
        }
        //#endregion

        //#region 表單檔案資料
        Dropzone.autoDiscover = false;
        recordFileDropzone = new Dropzone("#record-file-form", {
            url: "/Operation/SaveOperationRecordFile",
            acceptedFiles: "image/*, application/pdf,.doc,.docx,.xls,.xlsx",
            autoProcessQueue: false,
            parallelUploads: 5,
            maxFiles: 5,
            addRemoveLinks: true,
            uploadMultiple: true,
            dictRemoveFile: "移除",
            init: function (e) {

                var myDropzone = this;

                myDropzone.on("sending", function (file, xhr, data) {
                    if ((countOperationRecordFile + myDropzone.files.length) > 5) {
                        toast_warning("檔案總數量不可超過 5 張");
                        myDropzone.removeFile(file);
                        return;
                    } else {

                        data.append("Id", selected_id);
                        data.append("RecordFiles", file);

                    }
                });

            }
        });
        //#endregion

        //#region 產生檔案html
        function CreateRecordFileBox(dom, value, show_del_btn) {
            var str = "";
            str += '<div class="col-2  px-0 py-2 mx-2">';
            var split = value.fileName.split(".");
            var excel_format = ["xls", "xlsx"];
            var word_format = ["doc", "docx"];
            if (split[split.length - 1].toLowerCase() == "pdf") {
                str += '<a href="' + value.fileName + '" class="btn btn-info waves-effect waves-themed mb-3 mr-2" download><i class="fal fa-file-pdf" style="font-size: 1.5em; line-height: 2;"></i></a>';
            } else if (excel_format.indexOf(split[split.length - 1].toLowerCase()) > -1) {
                str += '<a href="' + value.fileName + '" class="btn btn-info waves-effect waves-themed mb-3 mr-2" download><i class="fal fa-file-excel" style="font-size: 1.5em; line-height: 2;"></i></a>';
            } else if (word_format.indexOf(split[split.length - 1].toLowerCase()) > -1) {
                str += '<a href="' + value.fileName + '" class="btn btn-info waves-effect waves-themed mb-3 mr-2" download><i class="fal fa-file-word" style="font-size: 1.5em; line-height: 2;"></i></a>';
            } else {
                str += '<img src="' + value.fileName + '" class="img-zoom" width="100%" />';
            }

            if (show_del_btn) {
                str += '<a href="javascript:;" class="del-operation-record-file-btn" data-id="' + value.id + '">';
                str += '<span class="badge border border-light rounded-pill bg-danger-500 position-absolute pos-top pos-right"><i class="fal fa-times"></i></span>';
                str += '</a>';
            }

            str += '</div>';
            dom.append(str);
        }
        //#endregion

        //#region 刪除檔案
        $('#record_files_div').on("click", "a.del-operation-record-file-btn", function () {

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

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

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

                    var url = "/Operation/DeleteOperationRecordFile";

                    var send_data = {
                        ReocdeId: selected_id,
                        SelectedId: selectedFileId
                    }

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

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

        //#region 匯出excel
        function ExportExcel() {
            var url = "/Operation/ExportOperationRecordExcel";
            var send_data = {
                CityIds: [3],
                PowerStationIds: [1]
            };
            $.post(url, send_data, function (rel) {
                if (rel.code != "0000") {
                    toast_error(rel.msg);
                    return;
                }
                $('#NoViewbody').empty();

                var str = "";
                rel.data.forEach(function (value, index) {
                    str += "<tr>" +
                        "<td>" + value.powerStationName + "</td>" +
                        "<td>" + value.formId + "</td>" +
                        "<td>" + value.workTypeText + "</td>" +
                        "<td>" + value.fixDo + "</td>" +
                        "<td>" + value.statusText + "</td>" +
                        "<td>" + value.workPersonName + "</td>" +
                        "<td>" + value.operationPredict + "</td>";

                        str += "<td>";
                        if (value.hyperLinks != undefined || value.hyperLinks != null) {
                            value.hyperLinks.forEach(function (value2, index) {
                                str += value2 + "<br>";
                            });
                        }
                        str += "</td>";

                        str += "<td>";
                        if (value.finishTime != undefined || value.finishTime != null || value.finishTime != "") {
                            //value.hyperLinks.forEach(function (value3, index) {
                            //    str += value3;
                            //});
                            str += value.finishTime ;
                        }
                        str += "</td>";

                        str += "</tr>";
                });

                $('#NoViewbody').append(str);

                $("#NoView").table2excel({
                    // 匯出的Excel文件的名稱
                    name: "abc",
                    // Excel檔案的名稱
                    filename: "test",
                    //檔案字尾名
                    fileext: ".xls",
                });
            }, 'json');
        }
        //#endregion

        //#region 查詢近30天
        function ChangeDate30() {
            var today = new Date();
            var dateLimit = new Date(new Date().setDate(today.getDate() - 30));

            var today_format = today.toISOString().slice(0, 10).replace(/-/g, "/");
            var dateLimit_format = dateLimit.toISOString().slice(0, 10).replace(/-/g, "/");

            datepicker.data('daterangepicker').setStartDate(dateLimit_format);
            datepicker.data('daterangepicker').setEndDate(today_format);

            $('#date-range').val(dateLimit_format + ' - ' + today_format);
            $('#date-range').trigger('change');
        }
        //#endregion

        //#region 改狀態
        function CheckStatus(type, e) {
            status = type;
            if ($(".status-type").hasClass("btn-success")) {
                $(".status-type").removeClass("btn-success").addClass("btn-secondary");
            }
            $(e).removeClass("btn-secondary").addClass("btn-success");
            if (status == 2) {
                operationRecordTable.column(10).visible(true);
            }
            else {
                operationRecordTable.column(10).visible(false);
            }
            operationRecordTable.ajax.reload();
        }
        //#endregion

        function Search() {
            Searchtype = true;
            AllidsType = false;
            AllpoweridsType = false;
            Allcity2();
        }
    </script>
}