let that;
let datatable = null;
let del_file = null;
const app =  {
    data() {
        return {
            selected_page: Cookies.get('selmodelfile_page') || 10,
            selectpage: [{ val: "10", text: "每页10条" }, { val: "20", text: "每页20条" }, { val: "30", text: "每页30条" }, { val: "10", text: "每页40条" }],
            datatable: null,
            // 数据
            select: [{ text: "全部", val: "" }, { text: "485Model", val: "485Model" }, { text: "BaseModel", val: "BaseModel" }, { text: "RCUModel", val: "RCUModel" }],
            // 数据
            selected: Cookies.get('selmodelfile')||"",
            // 数据
            rcudata: [],
            // 高度
            appheight: "",
            // 添加类型 v     
            add_type: 0,
            // 文件列表
            files_data: [],
            // 文件名  单独 方便筛选
            files_name: [],
            // 表单input 数量 
            files_ele_count: 0
        }
    },
    created() {
        that = this;
        setTimeout(function () { that.init(); }, 10);
        del_file = this.del_file;
    },
    methods: {
        init() {
            this.table_init();
            this.loc();
        },
        clickCallback: function (pageNum) {
            console.log(pageNum)
        },
        // 唤起文件选择
        click_file(type) {
            // 取消上传等按钮 取消唤醒
            if (type == -10 && this.files_name.length > 0) {
                this.init();
            }
            if (type != -1) {
                this.files_ele_count = 0;
                this.files_name = [];
                this.files_data = [];
                this.add_type = type
            }
            // 取消上传等按钮 取消唤醒
            if (type == -10) {
                return;
            }
            var str = 'filedata' + this.files_ele_count;
            // this.$refs[str].click();
            // VUE触发报错
            $(this.$refs[str]).click();
        },
        add_file() {
            let data = new window.FormData(this.$refs['addfile']);
            let class_ = $('#filedata').attr('class');
            let class_1 = $('#file_data').attr('class');
            // 移除是为了 防止多个弹窗 同时挤掉
            //$('#filedata').attr('class','');
            //$('#file_data').attr('class', '');
            let _data = that.files_data.concat();
            that.files_data = [];
            MyPost("/Api/AddModelFile", { isSwal: true, title: "上传中...", data, type: 1 }, (res) => {
                for (let i = 0; i < _data.length; i++) {
                    // 已经上传的文件不再上传
                    if (_data[i].isok > -2) {
                        continue;
                    }
                    _data[i].isok = res[_data[i].name];
                    if (res[_data[i].name]) {
                        var str = 'filedata' + i;
                        $(that.$refs[str]).val("");
                    }
                }
                that.files_data = _data.concat();
                //toastr.success('添加成功~');
            }, (err) => {
                toastr.error('网络繁忙~')
            }, () => {
                try {
                    setTimeout(function () {
                        $('#filedata').attr('class', class_);
                        $('#file_data').attr('class', class_1);
                    }, 200);
                } catch (e) {
                    console.log("completeback - err");
                }
            }
            );
        },
        filechange() {
            var str = 'filedata' + this.files_ele_count;
            var files = $('.filedata')[this.files_ele_count].files;
            for (let i of files) {
                if (i.type.toUpperCase() != "text/xml".toUpperCase()) {
                    this.$refs[str].value = null;
                    toastr.error('只能上传.XML格式的文件!');
                    return false;
                }
                if (this.files_name.indexOf(i.name) >= 0) {
                    $(this.$refs[str]).val("");
                    toastr.error('文件重复!');
                    return false;
                }
                this.files_name.push(i.name);
                this.files_data.push(i);
            }
            this.files_ele_count++;
        },
        del_file(e,id) {
            console.log(id)
                let index = -1;
                for (let i = 0; i < that.rcudata.data.length; i++) {
                    if (that.rcudata.data[i].data.MFD_ID == id) {
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                console.log("非法访问~");
                return;
                }
            Swal.fire({
                title: ' ',
                text: "您确定要删除文件:" + that.rcudata.data[index].data.XML_FileName + " ?",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.value) {
                    MyPost("/Api/DelModelFile", { isSwal: true, title: "正删除...", data: { id: that.rcudata.data[index].data.MFD_ID } }, (res) => {
                        if (res) {
                            try {
                            that.rcudata.data.splice(index,1);
                                toastr.success('删除成功~');
                                $(e).closest("tr").remove();
                            } catch (e) {
                                console.log(e)
                            }
                        }
                        else
                            toastr.error('删除失败~');
                    }, (err) => {
                        toastr.error('删除失败~');
                    })

                }
            })
        },
        rem_file: function (index) {
            this.files_data.splice(index, 1);
            this.files_name.splice(index, 1);
            var str = 'filedata' + index;
            $(this.$refs[str]).val("");
        },
        loc: function () {
            // 采用的局部 vue 所以这里 有些许 jquery
            let footloc = $('.main-footer').offset().top;
            $('.main-footer').hide();
            this.appheight = "calc(100vh - " + $('.table-responsive').offset().top + "px)";
        },
        ellipsis(value) {
            let var_ = "" + value
            let length_ = var_.length;
            let str = "";
            for (var i = length_; i < 4; i++) {
                str += "1";
            }
            return var_ + `<span style='opacity: 0;'>` + str + `</span>`;
        },
        table_init() {
            try {
                if (datatable != null) {
                    datatable.destroy();
                }
                $.fn.dataTable.ext.errMode = 'none';//屏蔽掉报错弹窗
                datatable = $('#dataTable').on('error.dt', function (e, settings, techNote, message) {
                    console.log(e, settings, techNote)
                    console.log('An error has been reported by DataTables: ', message);
                }).DataTable({
                    "data": null,
                    "ordering": true,
                    "paging": true,
                    "serverSide": true,
                    "ajax": function (datas, callback, settings) {
                        datas.type = that.selected;
                        MyPost("/Api/SelModelFile", { isSwal: true, data: datas }, (res) => {
                            that.rcudata = res || [];
                            Cookies.set('selmodelfile', that.selected, { expires: 7, path: window.location.pathname });
                            Cookies.set('selmodelfile_page', that.selected_page, { expires: 7, path: window.location.pathname });
                            callback(res);
                        }, (err) => {
                            toastr.error('网络繁忙~')
                        })
                    },
                    'iDisplayLength': that.selected_page,
                    "columns": [{
                        'sTitle': '',/*.substring(6)*/
                        'render': function (data, type, rcu) {
                            try {
                                let STR =
                                    `<div class="col-12 col-md-6">
                                <span>`+ that.ellipsis(rcu.data.MFD_ID) + `</span>
                                <button type="button" class= "`+ (rcu.data.Available == 1 ? 'btn btn-xs btn-success' : 'btn btn-xs btn-danger') + `">` + (rcu.data.Available == 1 ? '可 用' : '不可用') + `</button>
                                `+ rcu.data.UploadDateTime + `
                                </div>
                                <div class="col-md-6 col-12">
                                FilePath :  `+ rcu.data.Directory + `\\` + rcu.data.XML_FileName + ` 
                                </div>
                                <div class="col-md-6 col-12">
                                XLM_MD5 : `+ rcu.data.XLM_MD5 + `
                                </div>
                                <div class="col-md-6 col-12">
                                `+ rcu.size + ` 
                                <button type="button" onclick="del_file(this,`+ rcu.data.MFD_ID+`)" class="btn  btn-danger btn-xs">删除文件</button>
                                </div>`;
                                return STR;
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    }],
                    "fnCreatedRow": function (nRow, aData, iDataIndex) {
                        $(nRow).addClass('bg-white').addClass('shadow');
                        $(nRow).children("td").addClass('row');
                        return;
                    },
                    "searching": false,
                    "autoWidth": false,
                    "bDeferRender ": true,
                    "bLengthChange": false,
                    "language":
                    {
                        "sProcessing": "处理中...",
                        "sLengthMenu": "显示 _MENU_ 项结果",
                        "sZeroRecords": "没有匹配结果",
                        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                        "sInfoPostFix": "",
                        "sSearch": "搜索:",
                        "sUrl": "",
                        "sEmptyTable": "表中数据为空",
                        "sLoadingRecords": "载入中...",
                        "sInfoThousands": ",",
                        "oPaginate": {
                            "sFirst": "首页",
                            "sPrevious": "上页",
                            "sNext": "下页",
                            "sLast": "末页"
                        },
                        "oAria": {
                            "sSortAscending": ": 以升序排列此列",
                            "sSortDescending": ": 以降序排列此列"
                        }
                    }
                });
            } catch (e) {
                console.log(e)
            }
        }
    }

}

Vue.createApp(app).mount('#app');

$('#app').show();

