layui.use(['laytpl', 'table', 'jquery', 'form', 'miniTab', 'xmSelect', 'laydate', 'soulTable','upload'], function () {
    let $ = layui.jquery,
        table = layui.table,
        xmSelect = layui.xmSelect,
        miniTab = layui.miniTab,
        laydate = layui.laydate,
        soulTable = layui.soulTable,
        upload = layui.upload,
        form = layui.form;

    /** index page **/
    if ($('.location-index-page').length > 0) {
        miniTab.listen();

        let listUrl = $('#table-container').data('url');
        let insTb = table.render({
            elem: '#table-container',
            title: '订单列表',
            defaultToolbar: ['filter', 'exports', {
                title: '搜索'
                , layEvent: 'search'
                , icon: 'layui-icon-search'
            }],
            toolbar: '#toolbar-tpl',
            method: 'POST',
            url: listUrl,
            page: true,
            limit: 20,
            limits: [20, 50, 100, 200, 500, 1000],
            request: {
                pageName: 'page',
                limitName: 'size',
            },
            parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            },
            cols: [[
                {type: 'checkbox'},
                {
                    title: '#', width: 50, collapse: true, hide: true,children: [
                        {
                            title: '订单商品列表'
                            , url: function (row) {
                                //row 为当前行数据
                                // console.log(row);
                                return '/manager/mall/order/get-order-spu?coding=' + row.coding
                            },
                            parseData: function (res) {
                                return {
                                    "code": res.code, //解析接口状态
                                    "msg": res.msg, //解析提示文本
                                    "count": res.data.total, //解析数据长度
                                    "data": res.data.list //解析数据列表
                                };
                            },
                            toolEvent: function (obj, pobj) {
                                // obj 子表当前行对象
                                // pobj 父表当前行对象

                                let childId = this.id; // 通过 this 对象获取当前子表的id

                                if (obj.event === 'check-sku') {
                                    layer.confirm('本次操作将核销剩余所有数量,请确认操作', {icon: 3}, function (index) {
                                        $.post('/manager/mall/order/check-sku', {
                                            coding: obj.data.coding,
                                            id: obj.data.id,
                                            num: obj.data.not_check_num
                                        }, function (res) {
                                            layer.msg(res.msg);
                                            if (res.code === 0) {
                                                table.reload(childId)
                                            }
                                        });
                                        layer.close(index)
                                    })
                                }

                            }
                            // ,height: 300
                            , cols: [[
                                {type: 'checkbox', fixed: 'left'},
                                {field: 'spu_name', title: '商品名称', minWidth: 200},
                                {field: 'sku_name', title: '规格', minWidth: 180},
                                {field: 'num', title: '数量', minWidth: 165},
                                // {
                                //     field: 'is_virtual', title: '是否虚拟物品', minWidth: 180,templet: function (d) {
                                //         return d.is_virtual === 1 ? '是' : '否';
                                //     }
                                // },
                                // {
                                //     field: 'is_activity', title: '是否活动商品',minWidth: 150, templet: function (d) {
                                //         return d.is_activity === 1 ? '是' : '否';
                                //     }
                                // },
                                // {field: 'activity_text', title: '活动类型'},
                                // {
                                //     field: 'is_check', title: '已全部核销',minWidth: 150, templet: function (d) {
                                //         let text = d.is_check === 1 ? '是' : '否';
                                //         return d.is_virtual === 1 ? text : '无需核销';
                                //     }
                                // },
                                // {
                                //     field: 'not_check_num', title: '待核销数量', minWidth: 150,templet: function (d) {
                                //         return d.is_virtual === 1 ? d.not_check_num : '无';
                                //     }
                                // },
                                // {
                                //     field: 'check_type', title: '核验方式',minWidth: 150, templet: function (d) {
                                //         let text = d.check_type === 'frontend' ? '线下核销' : '后台核销';
                                //         return d.is_virtual === 1 ? text : '无需核销';
                                //     }
                                // },
                                // {field: 'check_by', title: '核验人', minWidth: 165},
                                // {minWidth: 100, fixed: 'right', title: '操作', templet: '#child-row-operate'}
                            ]]
                            , done: function () {

                            }
                        }
                    ]
                },
                {
                    field: 'coding', title: '订单编号', minWidth: 200, templet: function (d) {
                        return d.coding + '\t'; // 数字+\t 避免导出时长数字被转为科学计数
                    }
                },
                {field: 'created_at', title: '下单时间', width: 180},
                {field: 'paid_at', title: '支付时间', width: 180, hide: true},
                {field: 'status_text', title: '订单状态', minWidth: 100},
                {field: 'nickname', title: '用户昵称',minWidth: 150},
                // {field: 'real_name', title: '用户姓名',minWidth: 150},
                {field: 'phone',title: '电话',minWidth: 150},
                // {field: 'pick_self_text', title: '配送方式',minWidth: 150},
                // {field: 'is_score_text', title: '积分订单', minWidth: 150},
                {field: 'price', title: '实付金额', minWidth: 150},
                {field: 'score', title: '使用积分', minWidth: 150},
                {field: 'address', title: '收货信息', minWidth: 200},
                // 默认隐藏列
                {field: 'shipped_at', title: '发货时间', width: 160, hide: true},
                {field: 'express_number', title: '快递单号', minWidth: 150, hide: true},
                {field: 'express_code', title: '快递公司代号', minWidth: 150, hide: true},
                {field: 'express_name', title: '快递公司名称', minWidth: 150, hide: true},
                {field: 'accepted_at', title: '确认收货时间', width: 160, hide: true},
                {minWidth: 200, title: '操作', templet: '#row-operate'}
            ]],
            done: function () {
                Tools.setInsTb(insTb);
                soulTable.render(this)
            }
        });

        let option = {
            elem: '#upload-order'
            ,url: '/manager/upload/file'
            ,done: function(res, index, upload){ //上传后的回调
                console.log(res);
                if (res.code === 0 || res.code === 200) {
                    importFile(res.data.src);
                } else {
                    layer.msg('上传失败'+res.msg);
                }
            }
            ,accept: 'file' //允许上传的文件类型
            ,field: 'file_file'
            ,exts: 'xls'
            ,size: 50 //最大允许上传的文件大小
            //,……
        }

        upload.render(option)

        //监听工具条 注意区别toolbar和tool  toolbar是表头上的工具条 tool是行中的工具条
        table.on('toolbar(table-container)', function (obj) {
            let layEvent = obj.event;
            let insTb = Tools.getInsTb();
            let url = $($(this).context).data('href')
            let title = $($(this).context).data('title')
            let width = $($(this).context).data('width') ? $($(this).context).data('width') : '100%';
            let height = $($(this).context).data('height') ? $($(this).context).data('height') : '100%';

            // debugger;
            switch (layEvent) {
                // toolbar 刷新
                case 'refresh':
                    refreshTab(insTb);
                    return false;
                case 'import-file':
                    // TODO 待完善 第二次点击导入无效
                    upload.render(option)
                    // up.reload(option)
                    return false;
                // toolbar 搜索
                case 'search':
                    let search = $('.table-search-fieldset');
                    if (search.hasClass('div-show')) {
                        search.css('display', 'none').removeClass('div-show');
                    } else {
                        search.css('display', 'block').addClass('div-show');
                    }
                    return false;
                // toolbar 导出物流
                case 'export-list':
                    let checkStatus = table.checkStatus('table-container'); //idTest 即为基础参数 id 对应的值
                    let ids = [];
                    let type = 'all';//all=导出所有符合条件的待发货订单 only=指定ID
                    let isScore = $('#is-score').data('score');

                    if (checkStatus.data.length > 0) {
                        type = 'only';//查询全部
                        layer.confirm('此操作仅导出待发货订单', {icon: 3}, function (index) {
                            $(checkStatus.data).each(function (i, item) {
                                if (item.status === 'paid') {
                                    ids.push(item.id);
                                }
                            })

                            if (ids.length <= 0) {
                                layer.msg('请选择正确的待发货订单');
                                return false;
                            }

                            layer.close(index)

                            exportFile(type, ids, isScore);
                        })
                    } else {
                        exportFile(type, ids, isScore);
                    }

                    return false;
                default:
                    if (layEvent !== 'LAYTABLE_COLS' && layEvent !== 'LAYTABLE_EXPORT') {
                        openLayer(url, title, width, height);
                        return false;
                    }
            }
        });

        // 下单时间范围筛选
        laydate.render({
            elem: '#order-start-at',
            type: 'datetime',
        });
        laydate.render({
            elem: '#order-end-at',
            type: 'datetime',
        });

    }

    /** index page **/
    if ($('.location-course-page').length > 0) {
        miniTab.listen();

        let listUrl = $('#table-container').data('url');
        let insTb = table.render({
            elem: '#table-container',
            title: '订单列表',
            defaultToolbar: ['filter', 'exports', {
                title: '搜索'
                , layEvent: 'search'
                , icon: 'layui-icon-search'
            }],
            toolbar: '#toolbar-tpl',
            method: 'POST',
            url: listUrl,
            page: true,
            limit: 20,
            limits: [20, 50, 100, 200, 500, 1000],
            request: {
                pageName: 'page',
                limitName: 'size',
            },
            parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            },
            cols: [[
                {type: 'checkbox'},
                {
                    title: '#', width: 50, collapse: true, hide: true,children: [
                        {
                            title: '订单商品列表'
                            , url: function (row) {
                                //row 为当前行数据
                                // console.log(row);
                                return '/manager/mall/order/get-order-spu?coding=' + row.coding
                            },
                            parseData: function (res) {
                                return {
                                    "code": res.code, //解析接口状态
                                    "msg": res.msg, //解析提示文本
                                    "count": res.data.total, //解析数据长度
                                    "data": res.data.list //解析数据列表
                                };
                            },
                            toolEvent: function (obj, pobj) {
                                // obj 子表当前行对象
                                // pobj 父表当前行对象

                                let childId = this.id; // 通过 this 对象获取当前子表的id

                                if (obj.event === 'check-sku') {
                                    layer.confirm('本次操作将核销剩余所有数量,请确认操作', {icon: 3}, function (index) {
                                        $.post('/manager/mall/order/check-sku', {
                                            coding: obj.data.coding,
                                            id: obj.data.id,
                                            num: obj.data.not_check_num
                                        }, function (res) {
                                            layer.msg(res.msg);
                                            if (res.code === 0) {
                                                table.reload(childId)
                                            }
                                        });
                                        layer.close(index)
                                    })
                                }

                            }
                            // ,height: 300
                            , cols: [[
                                {type: 'checkbox', fixed: 'left'},
                                {field: 'spu_name', title: '商品名称', minWidth: 200},
                                {field: 'sku_name', title: '规格', minWidth: 180},
                                {field: 'num', title: '数量', minWidth: 165},
                            ]]
                            , done: function () {

                            }
                        }
                    ]
                },
                {
                    field: 'coding', title: '订单编号', minWidth: 200, templet: function (d) {
                        return d.coding + '\t'; // 数字+\t 避免导出时长数字被转为科学计数
                    }
                },
                {field: 'created_at', title: '下单时间', width: 180},
                {field: 'paid_at', title: '支付时间', width: 180, hide: true},
                {field: 'status_text', title: '订单状态', minWidth: 100},
                {field: 'nickname', title: '用户昵称',minWidth: 150},
                // {field: 'real_name', title: '用户姓名',minWidth: 150},
                // {field: 'phone',title: '电话',minWidth: 150},
                // {field: 'pick_self_text', title: '配送方式',minWidth: 150},
                // {field: 'is_score_text', title: '积分订单', minWidth: 150},
                {field: 'price', title: '实付金额', minWidth: 150},
                // {field: 'score', title: '使用积分', minWidth: 150},
                // {field: 'address', title: '收货信息', minWidth: 200},
                // 默认隐藏列
                // {field: 'shipped_at', title: '发货时间', width: 160, hide: true},
                // {field: 'express_number', title: '快递单号', minWidth: 150, hide: true},
                // {field: 'express_code', title: '快递公司代号', minWidth: 150, hide: true},
                // {field: 'express_name', title: '快递公司名称', minWidth: 150, hide: true},
                {field: 'accepted_at', title: '确认收货时间', width: 160, hide: true},
                {minWidth: 200, title: '操作', templet: '#row-operate'}
            ]],
            done: function () {
                Tools.setInsTb(insTb);
                soulTable.render(this)
            }
        });

        let option = {
            elem: '#upload-order'
            ,url: '/manager/upload/file'
            ,done: function(res, index, upload){ //上传后的回调
                console.log(res);
                if (res.code === 0 || res.code === 200) {
                    importFile(res.data.src);
                } else {
                    layer.msg('上传失败'+res.msg);
                }
            }
            ,accept: 'file' //允许上传的文件类型
            ,field: 'file_file'
            ,exts: 'xls'
            ,size: 50 //最大允许上传的文件大小
            //,……
        }

        upload.render(option)

        //监听工具条 注意区别toolbar和tool  toolbar是表头上的工具条 tool是行中的工具条
        table.on('toolbar(table-container)', function (obj) {
            let layEvent = obj.event;
            let insTb = Tools.getInsTb();
            let url = $($(this).context).data('href')
            let title = $($(this).context).data('title')
            let width = $($(this).context).data('width') ? $($(this).context).data('width') : '100%';
            let height = $($(this).context).data('height') ? $($(this).context).data('height') : '100%';

            // debugger;
            switch (layEvent) {
                // toolbar 刷新
                case 'refresh':
                    refreshTab(insTb);
                    return false;
                case 'import-file':
                    // TODO 待完善 第二次点击导入无效
                    upload.render(option)
                    // up.reload(option)
                    return false;
                // toolbar 搜索
                case 'search':
                    let search = $('.table-search-fieldset');
                    if (search.hasClass('div-show')) {
                        search.css('display', 'none').removeClass('div-show');
                    } else {
                        search.css('display', 'block').addClass('div-show');
                    }
                    return false;
                // toolbar 导出物流
                case 'export-list':
                    let checkStatus = table.checkStatus('table-container'); //idTest 即为基础参数 id 对应的值
                    let ids = [];
                    let type = 'all';//all=导出所有符合条件的待发货订单 only=指定ID
                    let isScore = $('#is-score').data('score');

                    if (checkStatus.data.length > 0) {
                        type = 'only';//查询全部
                        layer.confirm('此操作仅导出待发货订单', {icon: 3}, function (index) {
                            $(checkStatus.data).each(function (i, item) {
                                if (item.status === 'paid') {
                                    ids.push(item.id);
                                }
                            })

                            if (ids.length <= 0) {
                                layer.msg('请选择正确的待发货订单');
                                return false;
                            }

                            layer.close(index)

                            exportFile(type, ids, isScore);
                        })
                    } else {
                        exportFile(type, ids, isScore);
                    }

                    return false;
                default:
                    if (layEvent !== 'LAYTABLE_COLS' && layEvent !== 'LAYTABLE_EXPORT') {
                        openLayer(url, title, width, height);
                        return false;
                    }
            }
        });

        // 下单时间范围筛选
        laydate.render({
            elem: '#order-start-at',
            type: 'datetime',
        });
        laydate.render({
            elem: '#order-end-at',
            type: 'datetime',
        });

    }


    if ($('.location-operate-page').length > 0) {
        // 快递公司选择
        let expressEle = $('#express-list');
        let expressListJson = expressEle.data('menu') ? expressEle.data('menu') : [];
        xmSelect.render({
            el: '#express-list',
            paging: false,
            autoRow: true,
            radio: true,
            clickClose: true,
            name: 'express_id',
            tips: '请选择配送方式',
            direction: 'auto',
            height: '180px',
            model: {
                icon: 'show',
            },
            prop: {
                name: 'name',
                value: 'value',
            },
            theme: {
                color: '#1e84ff',
            },
            data: expressListJson,
            on: function (data) {

            }
        });
    }

    if ($('.location-detail-page').length > 0) {
        miniTab.listen();

        //监听行工具条
        table.on('tool(table-container)', function (obj) {
            let layEvent = obj.event;
            let insTb = Tools.getInsTb();

            switch (layEvent) {
                // 行 删除
                case 'check-sku':
                    layer.confirm('本次操作将核销剩余所有数量,请确认操作', {icon: 3}, function (index) {
                        $.post('/manager/mall/order/check-sku', {
                            coding: obj.data.coding,
                            id: obj.data.id,
                            num: obj.data.not_check_num
                        }, function (res) {
                            layer.msg(res.msg);
                            if (res.code === 0) {
                                refreshTab(insTb);
                            }
                        });
                        layer.close(index)
                    })
                    return false;
                //其他 默认为打开弹出层
                default:
                    openLayer(url, title, width, height);
                    return false;
            }
        });

        // 渲染表格
        let listUrl = $('#table-container').data('url');
        let insTb = table.render({
            elem: '#table-container',
            toolbar: '#toolbar-tpl-detail',
            defaultToolbar: [],
            url: listUrl,
            method: 'post',
            even: true,
            limits: [10, 20, 50, 100, 200, 500, 1000, 2000],
            request: {
                pageName: 'page',
                limitName: 'size',
            },
            parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            },
            page: true,
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'spu_name', title: '商品名称', minWidth: 200},
                {field: 'sku_name', title: '规格', minWidth: 180},
                {field: 'num', title: '数量', minWidth: 165},
                // {
                //     field: 'is_virtual', title: '是否虚拟物品', minWidth: 180,templet: function (d) {
                //         return d.is_virtual === 1 ? '是' : '否';
                //     }
                // },
                // {
                //     field: 'is_activity', title: '是否活动商品', minWidth: 165, templet: function (d) {
                //         return d.is_activity === 1 ? '是' : '否';
                //     }
                // },
                // {field: 'activity_text', title: '活动类型'},
                // {
                //     field: 'is_check', title: '已全部核销', minWidth: 165, templet: function (d) {
                //         let text = d.is_check === 1 ? '是' : '否';
                //         return d.is_virtual === 1 ? text : '无需核销';
                //     }
                // },
                // {
                //     field: 'not_check_num', title: '待核销数量', minWidth: 165, templet: function (d) {
                //         return d.is_virtual === 1 ? d.not_check_num : '无';
                //     }
                // },
                // {
                //     field: 'check_type', title: '核验方式', minWidth: 165, templet: function (d) {
                //         let text = d.check_type === 'frontend' ? '线下核销' : '后台核销';
                //         return d.is_virtual === 1 ? text : '无需核销';
                //     }
                // },
                // {field: 'check_by', title: '核验人', minWidth: 165},
                // {minWidth: 100, fixed: 'right', title: '操作', templet: '#child-row-operate'}
            ]],
            done: function () {
                Tools.setInsTb(insTb);
            }
        });
    }

    if ($('.location-course-detail-page').length > 0) {
        miniTab.listen();

        //监听行工具条
        table.on('tool(table-container)', function (obj) {
            let layEvent = obj.event;
            let insTb = Tools.getInsTb();

            switch (layEvent) {
                //其他 默认为打开弹出层
                default:
                    openLayer(url, title, width, height);
                    return false;
            }
        });

        // 渲染表格
        let listUrl = $('#table-container').data('url');
        let insTb = table.render({
            elem: '#table-container',
            toolbar: '#toolbar-tpl-detail',
            defaultToolbar: [],
            url: listUrl,
            method: 'post',
            even: true,
            limits: [10, 20, 50, 100, 200, 500, 1000, 2000],
            request: {
                pageName: 'page',
                limitName: 'size',
            },
            parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            },
            page: true,
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'spu_name', title: '课程名称', minWidth: 200},
                // {field: 'sku_name', title: '规格', minWidth: 180},
                {field: 'num', title: '数量', minWidth: 165},
            ]],
            done: function () {
                Tools.setInsTb(insTb);
            }
        });
    }

});

function exportFile(type, ids, isScore) {
    layui.use(['table', 'jquery'], function () {
        let $ = layui.jquery,
            table = layui.table;
        $.post('/manager/mall/order/export-order-list', {
            ids: ids,
            is_score: isScore,
            type: type
        }, function (res) {
            if (res.code === 0) {
                console.log(res.data);
                table.exportFile(res.data.header, res.data.data, 'xls'); //默认导出 csv,也可以为:xls
            } else {
                layer.msg(res.msg);
            }
        });
    });

}

function importFile(file) {
    layui.use(['table', 'jquery'], function () {
        let $ = layui.jquery;
        let index = layer.load();
        $.post('/manager/mall/order/import-order', {
            file: file
        }, function (res) {
            layer.close(index);
            if (res.code === 0) {
                refreshTab(insTb);
                layer.alert('操作成功,本次成功更新记录数:'+res.data.count, {icon: 6});
                // console.log(res.data);
            } else {
                layer.alert(res.msg);
            }
        });
    });

}