<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layuiAdmin 后台管理员</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta name="decorator" content="base" />
</head>
<body>

<div class="layui-fluid">
  <div class="layui-card">
    <%-- <div class="layui-form layui-card-header layuiadmin-card-header-auto" style="height:30px;">
         <div class="layui-form-item">
             <a href="${ctx}/systemSetup" style="cursor:pointer;">
                 <i class="layui-icon layui-icon-return layuiadmin-button-btn"></i><span style="margin-left:2px;">返回</span>
             </a>
         </div>
     </div>--%>
      <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title">
          <sfTags:pagePermission authFlag="XTSZ_GMQD_T" html='<a href="${ctx}/buyWay/toBuyWay"><li class="layui-this">购买渠道</li></a>'/>
        </ul>
      </div>
    <div class="layui-card-body">
      <table class="layui-hide" lay-skin="row" id="test" lay-filter="test"></table>
      <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
          <sfTags:pagePermission authFlag="GMQD_XZ_B" html='<button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon layui-icon-add-1"></i>新增</button>'/>
          <sfTags:pagePermission authFlag="GMQD_XG_B" html='<button class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</button>'/>
          <sfTags:pagePermission authFlag="GMQD_SC_B" html='<button class="layui-btn layui-btn-sm" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</button>'/>
        </div>
      </script>
    </div>
  </div>
</div>

<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script>
    var reg = /^\d{1,6}$/;
    var reg1 = /^.{1,10}$/;
    layui.use(['table','layer','laypage'], function(){
        $ = layui.$;
        table = layui.table;
        layer = layui.layer;
        laypage = layui.laypage;

        table.render({
            elem: '#test',
            height: 'full-150'
            , toolbar: '#toolbarDemo'
            , defaultToolbar: false
            , limits : [ 20, 50, 100 ]
            , limit:20
            , page : true //开启分页
            , url: '${ctx}/buyWay/getList'
            ,request: {
                pageName: 'pageNo' //页码的参数名称，默认：page
                ,limitName: 'PageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[
                {filed:'number', type: 'numbers',title:'序号'}
                , {field: 'id', type: 'checkbox'}
                , {field: 'mall_name', title: '购买渠道名称', sort: false, align: 'center'}
                , {field: 'sort', title: '排序', align: 'center'}
                , {field: 'update_time', title: '创建时间', sort: false, align: 'center'}
            ]],
            jump: function (obj) {
                console.log("jump");
            },
            done: function (res) {
                console.log(res);
            }
        });

        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    layer.open({
                        type: 2
                        ,title: '新增'
                        ,content: '${ctx}/buyWay/addBuyWayPop'
                        ,area: ['740px', '360px']
                        ,btn: ['确定', '取消']
                        ,yes: function(index, layero){
                            var iframeWindow = window['layui-layer-iframe'+ index]
                                ,submitID = 'LAY-user-front-submit'
                                ,submit = layero.find('iframe').contents().find('#'+ submitID);

                            //监听提交
                            var status = "ok";
                            iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                                var jsonArry = [];
                                var arr = [];
                                layero.find('iframe').contents().find(".contentBody").each(function (index) {
                                    var mallName = $(this).find("input[name='mallName']").val();
                                    var sort = $(this).find("input[name='sort']").val();
                                    if (!reg1.test(mallName)) {
                                        layer.msg("购买渠道名称长度需小于10位", {icon: 5, anim: 6});
                                        status = "no";
                                    }
                                    if (!reg.test(sort)) {
                                        layer.msg("排序只能是1-6位数字", {icon: 5, anim: 6});
                                        status = "no";
                                    }
                                    arr.push(mallName);
                                    if(isRepeat(arr)){
                                        layer.msg("购买渠道名称重复", {icon: 5, anim: 6});
                                        status="no";
                                    }
                                    if (!isBlank(mallName) && !isBlank(sort)) {
                                        var info = {
                                            mallName: mallName,
                                            sort: sort
                                        };
                                        jsonArry.push(info);
                                    }
                                });
                                if ("ok" == status) {
                                    $.ajax({
                                        type: 'post',
                                        data: {jsonData: JSON.stringify(jsonArry)},
                                        url: "${ctx}/buyWay/save",
                                        success: function (data) {
                                            if (data == '200') {
                                                layer.msg("添加成功！", {icon: 1});
                                                table.reload('test'); //数据刷新
                                                layer.close(index); //关闭弹层
                                            } else if (data == '202') {
                                                layer.msg("保存失败", {icon: 2});
                                            } else if (data == '205') {
                                                layer.msg("购买渠道已存在！", {icon: 2});
                                            } else {
                                                layer.msg("参数信息有误，请检查！", {icon: 2});
                                            }
                                            saveMark = false;
                                            return;
                                        },
                                        error: function (e) {
                                            layer.msg("请刷新！", {icon: 2});
                                            saveMark = false;
                                            return;
                                        }
                                    })
                                }
                            });
                            submit.trigger('click');
                        },
                        success : function(layero) {
                            layero.find('.layui-layer-btn').css('text-align', 'center');
                            layero.find('.layui-layer-btn').find(".layui-layer-btn0").css("background-color","#009688");
                        }
                    });
                    break;
                case 'edit':
                    var data = checkStatus.data;
                    if (data.length < 1) {
                        layer.msg("请选择您要编辑的数据！");
                    }else if(data.length > 1){
                        layer.msg("依次只能编辑一条数据！");
                    }else{
                        var site = data[0];
                        layer.open({
                            type: 2
                            ,title: '编辑'
                            , content: '${ctx}/buyWay/editBuyWayPop?nameOld='+site.mall_name+'&sortOld='+site.sort+''
                            ,area: ['400px', '217px']
                            ,btn: ['确定', '取消']
                            ,yes: function(index, layero){
                                var iframeWindow = window['layui-layer-iframe'+ index]
                                    ,submitID = 'LAY-user-front-submit'
                                    ,submit = layero.find('iframe').contents().find('#'+ submitID);

                                //监听提交
                                iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                                    var field = data.field; //获取提交的字段
                                    console.log(field)
                                    if(isBlank(field.mallName)){
                                        layer.msg("请填写购买渠道", {icon: 5, anim: 6});
                                        return false;
                                    }else if(isBlank(field.sort)){
                                        layer.msg("请填写排序", {icon: 5, anim: 6});
                                        return false;
                                    }else if(!reg.test(field.sort)){
                                        layer.msg("排序只能是数字", {icon: 5, anim: 6});
                                    }else{
                                        editMark(field,index,site.id);
                                    }
                                });
                                submit.trigger('click');
                            },
                            success : function(layero) {
                                layero.find('.layui-layer-btn').css('text-align', 'center');
                                layero.find('.layui-layer-btn').find(".layui-layer-btn0").css("background-color","#009688");
                            }
                        });
                    }
                    break;
                case 'del':
                    var data = checkStatus.data;
                    if (data.length < 1) {
                        layer.msg("请选择您要删除的数据！");
                    }else {
                        var ids = "";
                        for (var i = 0; i < data.length; i++) {
                            ids += data[i].id + ",";
                        }
                        layer.confirm('确认要删除选中数据吗？', {
                            icon:3,
                            btn: ['确定', '取消']//按钮
                        }, function (index) {
                            delData(ids, index);
                        });
                    }
                    break;
            };
        });
    });

    var noRepeat = false;
    function editMark(data, index,id) {
        if (noRepeat) {
            return;
        }
        noRepeat = true;
        $.ajax({
            url: '${ctx}/buyWay/editBuyWay',
            type: 'post',
            data: {
                id: id,
                name: data.mallName,
                sort: data.sort
            },
            success: function (data) {
                if (data.code=="200") {
                    layer.msg("编辑成功！",{icon:1});
                    table.reload('test'); //数据刷新
                    layer.close(index); //关闭弹层
                } else if(data.code=="204"){
                    layer.msg("编辑失败！",{icon:2});
                }else if(data.code=="205"){
                    layer.msg("购买渠道已存在！",{icon:2});
                }else{
                    layer.msg("请刷新！");
                }
            },
            complete: function () {
                noRepeat = false;
            }
        });
    }

    function delData(ids,index){
        $.ajax({
            url: '${ctx}/buyWay/delBuy',
            type: 'post',
            data: {
                ids: ids
            },
            success: function (data) {
                if (data=="200") {
                    layer.msg("删除成功！",{icon:1});
                    table.reload('test'); //数据刷新
                    layer.close(index); //关闭弹层
                } else if(data=="204"){
                    layer.msg("删除失败！",{icon:2});
                }else{
                    layer.msg("请刷新！");
                }
            },
            complete: function () {
                noRepeat = false;
            }
        });
    }

    function isBlank(val) {
        if (val == null || val == '' || val == undefined) {
            return true;
        }
        return false;
    }
    function isRepeat(arr){

        var hash = {};

        for(var i in arr) {

            if(hash[arr[i]]) //hash 哈希

                return true;

            hash[arr[i]] = true;

        }

        return false;

    }
</script>
</body>
</html>

