var startWorkFiles = {};
var table
var form
var upload
var example = null;
var pers = null;
// 设置全局变量以保存选中行信息
let ids = new Array();
$(function () {
    layui.use(['layer','form','table','upload'], function () {
        var layer = layui.layer;
        form = layui.form;
        table = layui.table;
        upload = layui.upload;

        init(table,form,'');

        var uploadIns = upload.render({
            elem: '#importBt', //绑定元素
            url: ctxPath + "/ma/sendoff/import",
            accept: 'file',   //允许上传的文件类型
            exts: 'xlsx|xls',
            auto: true,       //是否自动上传
            multiple: false,  //是否支持多文件上传
            choose: function(obj){ //选择文件后的回调函数

            },
            before:function(){
                layer.msg('数据导入中，请稍等。。。', {
                    icon: 4
                });
                this.data = {
                    "fileType": "sendoff"
                };
            },
            done: function(res, index, upload){ //上传完毕的回调函数
                layer.closeAll("loading");
                if (res.code == 200){
                    layer.msg('导入成功', {icon: 1, time: 2000},function () {
                        table.reload('layuiTable');
                    });
                } else {
                    layer.msg(res.msg,{icon:2})
                }

            }
            ,error: function(){
                layer.closeAll("loading");
                console.log("请求异常回调");
            }
        });

        $("#searchBt").click(function () {
            var keyWord = $("#keyWord").val();
            // var title = $("#title").val();
            init(table,form,keyWord)
        });

        $("#resetBt").click(function () {
            var keyWord = ''
            $("#keyWord").val("");
            // $("#title").val("");
            layui.form.render('select');
            init(table,form,keyWord)
        });


    });
    pers = checkPermission();
})


function init(table,form,keyWord) {
    table.render({
        elem: '#layuiTable'
        ,url: ctxPath + "/ma/sendoff/list?keyWord="+keyWord
        ,method:'post'
        ,cols: [[
            {type: 'checkbox', fixed: 'left'}
            , { field: 'ID', title: '序号',width:'3%', sort: true, type:'numbers'}
            , { field: 'cxPzTime', title: '冲销凭证日期',align:'center'}
            , { field: 'cxPzCode', title: '冲销凭证号',align:'center'}
            , { field: 'maCode', title: '物料号',align:'center'}
            , { field: 'maName', title: '物料名称',align:'center'}
            , { field: 'fhPzCode', title: '发货凭证号',align:'center'}
            , {field:'right', title: '操作',toolbar:"#barDemo",align:'center'}
        ]]
        ,limits: [5,10,20,50,100,500]  //一页选择显示3,5或10条数据
        , limit: 10  //一页显示5条数据
        , response: {
            statusCode: 200 //规定成功的状态码，默认：0
        }
        , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据，res为从url中get到的数据
            let result;
            if (res.count > 0) {
                if (this.page.curr) {
                    result = res.data.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
                } else {
                    result = res.data.slice(0, this.limit);
                }
            }
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": result //解析数据列表
            };
        }
        ,id: 'layuiTable'
        ,page: true //开启分页
        ,height: 600
    });

    table.on('tool(contact)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
            del(data.id);
        } else if(obj.event === 'edit'){
            edit(data.id);
        }
    });


}


/**
 * 新增
 */
function add(){
    localStorage.setItem('type','1')
    var index = layer.open({
        title: '新增',
        type: 2,
        content: './child/sendoffAddForm.html',
        area: ['80%', '70%'],
        maxmin: false,
        btn:['确定    ','取消'],
        yes:function(index,layero){
            var formSubmit=layer.getChildFrame('form', index);
            var submited = formSubmit.find('button')[0];
            // 触发点击事件，会对表单进行验证，验证成功则提交表单，失败则返回错误信息
            submited.click();
        },
        btn2:function(index,layero){

        }
    });
}

/**
 * 修改
 * */
function edit(id) {
    localStorage.setItem('type','2')
    $.ajax({
        type: 'post',
        url: ctxPath + '/ma/sendoff/getById',
        data: {
            "id":id
        },
        dataType: 'text',
        success: function (data) {
            var height = '80%';
            var width = '70%';
            var index = layer.open({
                title: '修改',
                type: 2,
                content: './child/sendoffForm.html',
                area: [width, height],
                maxmin: false,
                btn:['确定    ','取消'],
                success:function(layero,index){
                    var myIframe = window[layero.find('iframe')[0]['name']];
                    var fnc = myIframe.setData(data); //aaa()为子页面的方法
                },
                yes:function(index,layero){
                    var formSubmit=layer.getChildFrame('form', index);
                    var submited = formSubmit.find('button')[0];
                    // 触发点击事件，会对表单进行验证，验证成功则提交表单，失败则返回错误信息
                    submited.click();
                },
                btn2:function(index,layero){

                }
            });
        }
    })
}

/**
 * 删除
 * */
function del(id) {
    layer.confirm("确定删除吗？",function () {
        $.ajax({
            type: 'post',
            url: ctxPath + '/ma/sendoff/delete',
            data: {
                "id":id
            },
            success: function (data) {
                if(data.code == 200){
                    layer.alert('删除成功', {icon: 1},()=>{
                        location.reload();
                    });
                }else{
                    layer.alert('删除失败', {icon: 2});
                }

            }
        })
    })
}


function getData(day){
    var today=new Date()
    var targetday=today.getTime() +1000*60*60*24* day
    today.setTime(targetday)
    var tYear=today.getFullYear()
    var tMonth=today.getMonth()
    var tDate=today.getDate()
    tMonth=this.doHandMonth(tMonth+1)
    tDate=this.doHandMonth(tDate)
    return tYear +"-" + tMonth+"-"+tDate
}


function doHandMonth(month){
    var m=month
    if(month.toString().length==1){
        m="0"+month
    }
    return m
}

function batchDeleteBtn(){
    var selectData = layui.table.checkStatus('layuiTable').data;
    console.log(selectData);
    let ids = [];
    for (let i = 0; i < selectData.length; i++){
        ids.push(selectData[i].id)
    }
    console.log(ids);
    if(ids.toString() == ''){
        return layer.alert('请选择需要删除的数据',{icon: 0});
    }else{
        layer.confirm("确定删除所选 "+ids.length+" 条数据吗？",function () {
            $.ajax({
                type: 'delete',
                url: ctxPath + '/ma/sendoff/' + ids.toString(),
                success: function (data) {
                    if(data.code == 200){
                        layer.msg('删除成功', {icon: 1},function () {
                            table.reload('layuiTable');
                        });
                    }else{
                        layer.alert('删除失败', {icon: 2});
                    }

                }
            })
        })
    }
}

function exportData() {
    var index = layer.msg('数据导出中，请稍等。。。', {
        icon: 4
    });
    var token = localStorage.getItem("token");
    var djCode = $("#djCode").val();
    var maCode = $("#maCode").val();
    var param = {
        djCode:djCode,
        maCode:maCode
    }
    var url = ctxPath + "/ma/sendoff/export?param=" + encodeURIComponent(JSON.stringify(param));
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    //设置xhr请求的超时时间
    xhr.timeout = 100000;
    //设置响应返回的数据格式
    xhr.responseType = "blob";  // 转换流
    xhr.setRequestHeader("token", token);
    //构造表单数据
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = this.response;
            var a = document.createElement("a");
            var url = window.URL.createObjectURL(blob);
            a.href = url;
            layer.close(index);
            a.download = "发货冲销对应表-导出.xlsx"; // 文件名
        } else if (this.status === 401) {
            localStorage.removeItem("token");
            layer.msg('用户登录过期,请重新登录', {icon: 5, time: 2000}, function () {
                location.href = ctxPath + '/login.html';
            });
        }
        a.click();
        window.URL.revokeObjectURL(url);
    };
    xhr.send();
}

function downloadFile() {
    var token = localStorage.getItem("token");
    window.location.href = ctxPath + "/download/download?filename=发货冲销对应表-导入模板.xlsx&token=" + token;
}

