var SUCCESS = 'success';
var ERROR = 'error';

var serverErrorMessage = 'Oops, something wrong :(';

$(document).ready(function () {
    $('#pestDataTable').dataTable({


        "ajax": {
            "url": "/list/",
            "dataType": "json",

        },
        dom: 'Bfrtip',
        buttons: [
            {
                "extend": 'excel',//使用 excel扩展
                "text": '导出',// 显示文字
                "exportOptions": {
                    //自定义导出选项
                    //如：可自定义导出那些列，那些行
                    //TODO...
                     'modifier': {
                         //'page': 'current'
                         selected: true
                     }
                }
            }
        ],

        selected: false,

        "columns": [

            {
                data: "pk",

                "render": function (data) {
                    return '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline"><input type="checkbox" class="checkbox" value="' + data + '" /><span></span></label>';
                }
            },
            {"data": "fields.pestname"},
            {"data": "fields.date"},
            {"data": "fields.adressid"},
            {"data": "fields.researchpeople"},
            {"data": "fields.remark", visible:false},
            {
                data: "pk",
                "render": function (data) {
                    return '<i id=" ' + data + ' " class="edit-button glyphicon glyphicon-edit cursorPointer" ></i>';
                }
            },
            {
                data: "pk",
                "render": function (data) {
                    return '<i id=" ' + data + ' " class="remove-button glyphicon glyphicon-trash cursorPointer"></i>';
                }
            }

        ]
    });



    var tableTree = $('#pestDataTable').DataTable();

    $("body").on('checked','.mt-checkbox',function () {
        tableTree.rows( { selected: true } ).data();
    });

    // Delete employee event
    $("body").on('click', '.remove-button', function () {
        var currentRow = $(this);
        var treeId = $(this).attr('id').trim();
        bootbox.confirm("Are you sure?", function (result) {
            if (result) {
                $.ajax({
                    url: "/del_pest/" + treeId,
                    type: "GET",
                    data: {Id: treeId},
                    success: function (response) {
                        if (response.status == SUCCESS) {
                            showSuccessAlert(response.msg);
                            tableTree.row(currentRow.parents('tr')).remove().draw();
                        } else {
                            showErrorAlert(serverErrorMessage);
                        }
                    },
                    error: function () {
                        showErrorAlert(serverErrorMessage);
                    }
                });
            } else {
                //
            }
        });
    });


    // Edit employee event
    $("body").on('click', '.edit-button', function () {

        var treeId = $(this).attr('id').trim();
        $('#gsmmEditForm input[id=file]').val("")
        $('#gsmmEditModal').modal('show');
        $.ajax({
            url: "/pestdic/0",
            type: "GET",
            "dataType": "json",
            async: false,
            success: function (response) {
                $('#gsmmEditForm select[name=pestname]').empty();
                $('#gsmmEditForm select[name=pestname]').append($('<option>').text("-请选择-").attr('value', 0));
                $.each(response.data, function (i, obj) {
                    $('#gsmmEditForm select[name=pestname]').append($('<option>').text(obj.fields.pestname).attr('value', obj.fields.id));
                });
            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
        $.ajax({
            url: "/researchpeople/0",
            type: "GET",
            "dataType": "json",
            async: false,
            success: function (response) {
                $('#gsmmEditForm select[name=researchperson]').empty();
                $('#gsmmEditForm select[name=researchperson]').append($('<option>').text("-请选择-").attr('value', 0));
                $.each(response.data, function (i, obj) {
                    $('#gsmmEditForm select[name=researchperson]').append($('<option>').text(obj.fields.username).attr('value', obj.fields.id));
                });
            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
        $.ajax({
            url: "/pestlist/" + treeId,
            type: "GET",
            data: {id: treeId},
            success: function (response) {
                $('#gsmmEditForm input[name=id]').val(treeId);
                $.each(response.data[0].fields, function (key, value) {
                    if (key == "date") {
                        $('#gsmmEditForm input[name="' + key + '"]').val(value);
                    }
                    else if (key == "adressid") {
                        $('#gsmmEditForm input[name="' + key + '"]').val(value);
                    } else if (key == "pestname") {
                        $('#gsmmEditForm select[name="' + key + '"]').val(value);
                    } else if (key == "pestfirstgrade") {
                        $('#gsmmEditForm select[name="' + key + '"]').val(value);
                    } else if (key == "pestsecondgrade") {
                        $('#gsmmEditForm select[name="' + key + '"]').val(value);
                    } else if (key == "researchpeople") {
                        $('#gsmmEditForm select[name=researchperson]').val(value);
                    } else if (key == "remark") {
                        $('#gsmmEditForm textarea[name="' + key + '"]').val(value);
                    } else if (key == "longtitude") {
                        $('#gsmmEditForm input[name="' + key + '"]').val(value);
                    } else if (key == "latitude") {
                        $('#gsmmEditForm input[name="' + key + '"]').val(value);
                    } else {
                        $('#gsmmEditForm input[name="' + key + '"]').val(value);
                    }
                });
                var picurl1 = $('#gsmmEditForm input[name=pestpicurl1]').val()
                $("#gsmmEditForm img[id=pestpic1]").attr("src", picurl1);
                $("#pestpic1").show();
                var picurl2 = $('#gsmmEditForm input[name=pestpicurl2]').val()
                $("#gsmmEditForm img[id=pestpic2]").attr("src", picurl2);
                $("#pestpic2").show();

            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
    });


    $('#gsmmModal').on('shown.bs.modal', function () {
        $('#gsmmForm').trigger("reset");
        $("#gsmmForm img[id=pestpic1]").attr("src", "");
        $("#gsmmForm img[id=pestpic2]").attr("src", "");
        $("#gsmmForm img[id=pestpic1]").hide();
        $("#gsmmForm img[id=pestpic2]").hide();
        $.ajax({
            url: "/pestdic/0",
            type: "GET",
            "dataType": "json",
            success: function (response) {
                $('#gsmmForm select[name=pestname]').empty();
                $('#gsmmForm select[name=pestname]').append($('<option>').text("-请选择-").attr('value', "0"));
                $.each(response.data, function (i, obj) {
                    $('#gsmmForm select[name=pestname]').append($('<option>').text(obj.fields.pestname).attr('value', obj.fields.id));
                });

            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
        $.ajax({
            url: "/researchpeople/0",
            type: "GET",
            "dataType": "json",
            success: function (response) {
                $('#gsmmForm select[name=researchperson]').empty();
                $('#gsmmForm select[name=researchperson]').append($('<option>').text("-请选择-").attr('value', 0));
                $.each(response.data, function (i, obj) {
                    $('#gsmmForm select[name=researchperson]').append($('<option>').text(obj.fields.username).attr('value', obj.fields.id));
                });

            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });


    });


//增加页面select联动事件
    $('#pestname').change(function () {
        var keId = $("#pestname").find("option:selected").val().toString();
        $.ajax({
            url: "/pestdic/" + keId,
            type: "GET",
            data: {id: keId},
            "dataType": "json",
            success: function (response) {
                $('#pestfirstgrade').empty();
                $('#pestfirstgrade').append($('<option>').text("-请选择-").attr('value', 0));
                $.each(response.data, function (i, obj) {
                    $('#pestfirstgrade').append($('<option>').text(obj.fields.pestfirstgrade).attr('value', obj.fields.id));
                });
            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
    });


    $('#pestfirstgrade').change(function () {
        var keId = $("#pestfirstgrade").find("option:selected").val().toString();
        $.ajax({
            url: "/pestdic/" + keId,
            type: "GET",
            data: {id: keId},
            "dataType": "json",
            success: function (response) {
                $('#pestsecondgrade').empty();
                $('#pestsecondgrade').append($('<option>').text("-请选择-").attr('value', 0));
                $.each(response.data, function (i, obj) {
                    $('#pestsecondgrade').append($('<option>').text(obj.fields.pestsecondgrade).attr('value', obj.fields.id));
                });
            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
    });

     $('#gsmmForm input[id=picupload1]').click(function (event) {
        event.preventDefault();
        var imgVal = $('#gsmmForm input[id=file]').val();

        /*if (imgVal.empty()) {
            alert("图片为空，请选择后上传!");
        }*/
        /*else {*/
        var file1 = $('#gsmmForm input[id=file]').get(0).files[0];
        var formData = new FormData();
        formData.append('file', file1);


            $.ajax({
                url: '/uploadpic/',
                data: formData,
                type: 'POST',
                contentType: false,
                processData: false,
                success: function (data) {
                    alert("图片上传成功");
                    $('#gsmmForm input[id=pestpicurl1]').val(data);
                    $("#gsmmForm img[id=pestpic1]").attr("src", data);
                    $("#gsmmForm img[id=pestpic1]").show();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus + ': ' + errorThrown);
                }
            });
       /* }*/
    });

    $('#gsmmForm input[id=picupload2]').click(function (event) {
        event.preventDefault();
        var file1 = $('#gsmmForm input[id=file]').get(0).files[0];
        var formData = new FormData();
        formData.append('file', file1);

        $.ajax({
            url: '/uploadpic/',
            data: formData,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function (data) {
                alert("图片上传成功");
                $('#gsmmForm input[id=pestpicurl2]').val(data);
                $("#gsmmForm img[id=pestpic2]").attr("src", data);
                $("#gsmmForm img[id=pestpic2]").show();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ': ' + errorThrown);
            }
        });

    });
//更新页面select联动事件
    $('#gsmmEditForm select[name=pestname]').change(function () {
        var keId = $('#gsmmEditForm select[name=pestname]').find("option:selected").val().toString();
        $.ajax({
            url: "/pestdic/" + keId,
            type: "GET",
            data: {id: keId},
            "dataType": "json",
            success: function (response) {
                $('#gsmmEditForm select[name=pestfirstname]').empty();
                $('#gsmmEditForm select[name=pestfirstname]').append($('<option>').text("-请选择-").attr('value', 0));
                $.each(response.data, function (i, obj) {
                    $('#gsmmEditForm select[name=pestfirstname]').append($('<option>').text(obj.fields.pestfirstname).attr('value', obj.fields.id));
                });
            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
    });

    $('#gsmmEditForm select[name=pestfirstgrade]').change(function () {
        var shuId = $('#gsmmEditForm select[name=pestfirstgrade]').find("option:selected").val().toString();
        $.ajax({
            url: "/pestdic/" + shuId,
            type: "GET",
            data: {id: shuId},
            "dataType": "json",
            success: function (response) {
                $('#gsmmEditForm select[name=pestsecondgrade]').empty();
                $('#gsmmEditForm select[name=pestsecondgrade]').append($('<option>').text("-请选择-").attr('value', 0));
                $.each(response.data, function (i, obj) {
                    $('#gsmmEditForm select[name=pestsecondgrade]').append($('<option>').text(obj.fields.pestsecondgrade).attr('value', obj.fields.id));
                });
            },
            error: function () {
                showErrorAlert(serverErrorMessage);
            }
        });
    });


    $('#gsmmEditForm input[id=picupload1]').click(function (event) {
        event.preventDefault();
        var imgVal = $('#gsmmEditForm input[id=file]').val();

        /*if (imgVal.empty()) {
            alert("图片为空，请选择后上传!");
        }*/
        /*else {*/
        var file1 = $('#gsmmEditForm input[id=file]').get(0).files[0];
        var formData = new FormData();
        formData.append('file', file1);


            $.ajax({
                url: '/uploadpic/',
                data: formData,
                type: 'POST',
                contentType: false,
                processData: false,
                success: function (data) {
                    alert("图片上传成功");
                    $('#gsmmEditForm input[id=pestpicurl1]').val(data);
                    $("#gsmmEditForm img[id=pestpic1]").attr("src", data);
                    $("#pestpic1").show();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus + ': ' + errorThrown);
                }
            });
       /* }*/
    });

    $('#gsmmEditForm input[id=picupload2]').click(function (event) {
        event.preventDefault();
        var file1 = $('#gsmmEditForm input[id=file]').get(0).files[0];
        var formData = new FormData();
        formData.append('file', file1);

        $.ajax({
            url: '/uploadpic/',
            data: formData,
            type: 'POST',
            contentType: false,
            processData: false,
            success: function (data) {
                alert("图片上传成功");
                $('#gsmmEditForm input[id=pestpicurl2]').val(data);
                $("#gsmmEditForm img[id=pestpic2]").attr("src", data);
                $("#pestpic2").show();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ': ' + errorThrown);
            }
        });

    });
// Show success alert message
    var showSuccessAlert = function (message) {
        $.toaster({priority: 'success', title: 'Success', message: message});
    }

// Show error alert message
    var showErrorAlert = function (message) {
        $.toaster({priority: 'danger', title: 'Error', message: message});
    }

// Convert form data in JSON format
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                if (this.name == 'id' || this.name == 'city' || this.name == 'county' || this.name == 'ke' || this.name == 'shu' || this.name == 'cname' || this.name == 'treelevel') {
                    o[this.name] = parseInt(this.value) || 0;
                } else {
                    o[this.name] = this.value || '';
                }
            }
        });

        return JSON.stringify(o);
    };

// Handling form submission for create new employee
    $('#gsmmForm').on('submit', function (e) {
        var pestname = $('#gsmmForm select[name=pestname]').find("option:selected").val();
        var researchperson = $('#gsmmForm select[name=researchperson]').find("option:selected").val();
        if (pestname == 0 || researchperson == 0) {
            alert("虫种和调查人均不能为空，请选择后再保存数据")
            return false
        } else {
            var pestData = $("#gsmmForm").serializeObject();
            var formData = JSON.parse(pestData)
            e.preventDefault();
            $.ajax({
                url: "/create/",
                type: 'POST',
                data: formData,
                dataType: 'JSON',
                success: function (arg) {
                    if (arg.status) {
                        $('#gsmmModal').modal('hide');
                        showSuccessAlert("添加信息成功");
                    } else {
                        $('#gsmmpModal').modal('hide');
                        showErrorAlert(arg.message);
                    }
                },
                error: function () {
                    $('#gsmmModal').modal('hide');
                    showErrorAlert(serverErrorMessage);
                }

            });
            return false;
        }
    });

// Handling form submission for update employee
    $('#gsmmEditForm').on('submit', function (e) {
        var pestname = $('#gsmmEditForm select[name=pestname]').find("option:selected").val();
        var researchperson = $('#gsmmEditForm select[name=researchperson]').find("option:selected").val();
        if (pestname == 0 || researchperson == 0) {
            alert("虫种和调查人均不能为空，请选择后再保存数据")
            return false
        } else {
            var pestData = $("#gsmmEditForm").serializeObject();
            var formData = JSON.parse(pestData)
            e.preventDefault();
            $.ajax({
                url: '/update/',
                type: 'POST',
                data: formData,
                dataType: 'JSON',
                success: function (arg) {
                    if (arg.code == 1000) {
                        alert("信息更改成功！！")
                        showSuccessAlert("信息更改成功！！");
                        window.location.reload();
                    } else {
                        alert(arg.message);
                    }
                }
            });

            return false;
        }
    });
});