let tableApplySNBToCNT;
let tree;
let startDate = new Date(new Date(new Date().toLocaleDateString()).getTime()),
    endDate = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
let snbStartDate = startDate, snbEndDate = endDate;
let applyState = 0;
layui.use(['element', 'form', 'table', 'layer', 'laydate', 'tree', 'util'], function () {
    let table = layui.table;
    let form = layui.form;//select、单选、复选等依赖form
    let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    let laydate = layui.laydate;
    tree = layui.tree;
    let height = document.documentElement.clientHeight;

    tableApplySNBToCNT = table.render({
        elem: '#applySnbTable'
        , url: ctx + "/sys/sysProperty/findApplySnbToCntPage"
        , method: 'POST'
        //请求前参数处理
        , request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'rows' //每页数据量的参数名，默认：limit
        }
        , where: {
            isState: applyState, sidx: "desc", sord: "createTime"
        }
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'records' //规定数据总数的字段名称，默认：count
            , dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            // console.log("返回的地址数据：", data);
            //这里应该是反回一个用户，后台做成了页面数据。但是只带一条数据
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "records": data.records, //解析数据长度
                "rows": data.rows //解析数据列表
            };
        }
        , toolbar: '#applySnbTableToolbarDemo'
        , title: 'SNB申请列表'
        , cols: [
            [
                {type: 'checkbox', fixed: 'left'},
                {
                    field: 'isState', title: '申请状态', sort: true, templet: function (d) {
                        if (d.isState == 0) {
                            return '<span style="color: green">申请中</span>';
                        } else if (d.isState == 1) {
                            return '<span style="color: green">申请成功</span>';
                        } else if (d.isState == 2) {
                            return '<span style="color: red ">申请驳回</span>';
                        } else if (d.isState == 3) {
                            return '<span style="color: red ">进入兑换流程</span>';
                        } else {
                            return '待添加：' + d.isState;
                        }
                    }
                }
                , {field: 'id', title: 'ID'}
                , {field: 'userId', title: '用户id', hidden: true}
                , {field: 'address', title: '用户address'}
                , {field: 'snb', title: '申请的Snb', sort: true}
                , {field: 'snbDescribe', title: '描述'}
                , {field: 'count',title:'申请下标'}
                , {field: 'createTime', title: '创建时间', sort: true}
                , {field: 'updateTime', title: '更新时间', sort: true}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
            ]]
        , defaultToolbar: ['', 'exports', 'print']
        , page: true
        , height: height
        , cellMinWidth: 80
        , autoSort: false
    });


    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
        let data = obj.data;
        switch (obj.event) {
            case 'applySnbTableReload':
                applySnbTableReloadFunction();
                break;
            case 'batchApproval':
                let checkStatusApproval = table.checkStatus('applySnbTable'), dataApproval = checkStatusApproval.data,
                    dataApprovalId = [];
                if (dataApproval.length > 0) {
                    for (let i in dataApproval) {
                        dataApprovalId.push(dataApproval[i].id);
                    }

                    layer.confirm('确定同意吗？', {icon: 3, title: '提示信息'}, function (index) {
                        let _loadingIndex = layer.msg('操作中，请稍候', {icon: 16, time: false, shade: 0.8});
                        let postData = {
                            isState: 1,
                            applyIdList: dataApprovalId.join(",")
                        };
                        $.post(ctx + "/sys/sysProperty/updateApplySnbToCntDataList", postData, function (res) {
                            layer.close(_loadingIndex);
                            if (!res.flag) {
                                layer.msg(res.msg, {icon: 2, time: 2000}, function () {
                                });
                                return;
                            }
                            applySnbTableReloadFunction();
                        });

                        layer.close(index);

                    })
                } else {
                    layer.msg("请选择需要通过的行");
                }
                break;
            case 'batchRejection':
                let checkStatusReject = table.checkStatus('applySnbTable'), dataReject = checkStatusReject.data,
                    dataRejectId = [];
                if (dataReject.length > 0) {
                    for (let i in dataReject) {
                        dataRejectId.push(dataReject[i].id);
                    }
                    layer.confirm('确定驳回吗？', {icon: 3, title: '提示信息'}, function (index) {
                        let _loadingIndex = layer.msg('操作中，请稍候', {icon: 16, time: false, shade: 0.8});
                        let postData = {
                            isState: 2,
                            applyIdList: dataRejectId.join(",")
                        };
                        $.post(ctx + "/sys/sysProperty/updateApplySnbToCntDataList", postData, function (res) {
                            layer.close(_loadingIndex);
                            if (!res.flag) {
                                layer.msg(res.msg, {icon: 2, time: 2000}, function () {
                                });
                                return;
                            }
                            applySnbTableReloadFunction();
                        });

                        layer.close(index);

                    })
                } else {
                    layer.msg("请选择需要驳回的行");
                }
                break;
            case 'getCheckLength':
                let checkStatus2 = table.checkStatus('applySnbTable'), data2 = checkStatus2.data;
                layer.msg('选中了：' + data2.length + ' 个');
                break;
            case 'isAll':
                let checkStatus3 = table.checkStatus('applySnbTable');
                layer.msg(checkStatus3.isAll ? '全选' : '未全选')
                break;
        }
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) {
        let data = obj.data;
        switch (obj.event) {
            case 'edit':
                //编辑
                // console.log("edit");
                //回显操作表单
                // $("#comUserForm").form(data);
                // form.render();
                break;
            case 'agree':
                if (!data.id) {
                    layer.msg("编辑列表不存在", {icon: 2, time: 1000}, function () {
                    });
                    return;
                }
                data.isState = 1;   //同意申请 1
                $.post(ctx + "/sys/sysProperty/updateApplySnbToCntData", data, function (res) {
                    if (!res.flag) {
                        layer.msg(res.msg, {icon: 2, time: 2000}, function () {
                        });
                        return;
                    }
                    obj.update(res.data);
                });
                break;
            case 'reject':
                if (!data.id) {
                    layer.msg("编辑列表不存在", {icon: 2, time: 1000}, function () {
                    });
                    return;
                }
                data.isState = 2;       //驳回申请 2
                $.post(ctx + "/sys/sysProperty/updateApplySnbToCntData", data, function (res) {
                    if (!res.flag) {
                        layer.msg(res.msg, {icon: 2, time: 2000}, function () {
                        });
                        return;
                    }
                    obj.update(res.data);
                });
                break;
        }
    });


    let $ = layui.$, active = {
        reload: function () {
            let addressReload = $('#addressReload');
            // console.log("reload");
            tableApplySNBToCNT.reload({
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                , method: 'POST'
                , url: ctx + "/sys/sysProperty/findApplySnbToCntPage"
                , where: {
                    address: addressReload.val().length != 0 ? addressReload.val() : null,
                    isState: applyState
                }
                , done: function (res, curr, count) {
                    // console.log(res, curr, count);
                    // this.where={};
                    //不清空，有问题：搜索条件会保留
                    //清空，  有问题：分页的时候没有搜索条件了,分页会受到影响
                }
            });

        },

        exports: function () {
            $.post(ctx + "/sys/sysProperty/findBetweenApplySnbToCntDataPage", {
                beginTime: commonUtil.parseTime(startDate),
                endTime: commonUtil.parseTime(endDate)
            }, function (res) {
                // console.log(res);
                table.exportFile(tableApplySNBToCNT.config.id,res.data,'xls');
            });
        }
    };

    laydate.render({
        elem: '#cntDate'
        , type: 'datetime'
        , value: commonUtil.parseTime(startDate) + ' - ' + commonUtil.parseTime(endDate)
        , isInitValue: true
        , range: true
        , done: function (_value, _date, _endDate) {
            // console.log(_value, _date, _endDate)
            let _array = _value.split(' - ');
            startDate = _array[0];
            endDate = _array[1];
            // console.log(startDate, endDate)
        }
    });

    $('.addressTable .layui-btn').on('click', function () {
        let type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    // console.log(applyState,$("#applyState").val(), $("#applyAutoExamine").val())
    // $("#applyContainer").find("[name='applyState'][value='" + $("#applyState").val() + "']").attr("checked", true);

    // element.tabChange('test', layid);

    element.on('tab(test)', function (data) {
        applyState = data.index;
        tableApplySNBToCNT.reload({
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , method: 'POST'
            , url: ctx + "/sys/sysProperty/findApplySnbToCntPage"
            , where: {
                isState: data.index
            } , done: function (res, curr, count) {
                console.log(applyState)

                // if(0 === applyState){
                //     $('.layuibtn1').css("display","inline-block");
                //     $('.layuibtn2').css("display","inline-block");
                //     $('.layuibtn3').css("display","inline-block");
                //     $('.layuibtn4').css("display","inline-block");
                //     $('.layuibtn5').css("display","inline-block");
                // }else{
                //
                //     $('.layuibtn1').css("display","inline-block");
                //     $('.layuibtn2').css("display","none");
                //     $('.layuibtn3').css("display","none");
                //     $('.layuibtn4').css("display","none");
                //     $('.layuibtn5').css("display","none");
                // }
            }
        });
    });

    //radio checkbox
    $("#sysSettingTaskForm").find("[name='applyAutoExamine'][value='" + $("#applyAutoExamine").val() + "']").attr("checked", true);
    form.render();
});

function applySnbTableReloadFunction() {
    tableApplySNBToCNT.reload({
        page: true
        , method: 'POST'
        , url: ctx + "/sys/sysProperty/findApplySnbToCntPage"
        , done: function (res, curr, count) {
            // console.log(res, curr, count);
            // this.where={};
            //不清空，有问题：搜索条件会保留
            //清空，  有问题：分页的时候没有搜索条件了,分页会受到影响
        }
    });
}

/**
 * 提交保存
 */
function sysSettingTaskFormSave() {
    let serializeObject = $("#sysSettingTaskForm").serializeObject();
    $.post(ctx + "/sys/sysSettingTask/save", serializeObject, function (data) {
        layer.msg("修改成功！", {icon: 1, time: 2000}, function () {
        });
        $("#sysSettingTaskForm").form(data.data);
        $("#applyAutoExamine").val(data.data.applyAutoExamine)
    });
}

