  <title>代码生成器</title>

  <div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
      <a lay-href="">主页</a>
      <a><cite>代码生成器</cite></a>
    </div>
  </div>
  
  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-header">表单选择</div>
          <div class="layui-card-body">
            <div class="table-btn" style="margin-bottom: 10px;">
              表名：
              <div class="layui-inline">
                <input class="layui-input" name="tableName" id="tableName" autocomplete="off">
              </div>
              <button class="layui-btn layui-btn-primary" data-type="reload" style="line-height:5px">
                <i class="layui-icon layui-icon-search"/>查询
              </button>
              <button class="layui-btn layui-btn-normal" data-type="codegen" style="line-height:5px">
                <i class="layui-icon layui-icon-code-circle"/> 代码生成
              </button>
            </div>
            <table class="layui-hide" id="table-codegen"></table>
          </div>
        </div>
      </div>
    </div>
  </div>

  
  <script>
  layui.use(['admin', 'table'], function(){

    var table = layui.table
            ,$ = layui.$
            , form = layui.form
            , admin = layui.admin;

    var TABLE_ID = 'table-codegen';

    table.render({
      elem: '#'+TABLE_ID
      ,url: 'generator/page'
      ,cols: [[
        {type:'checkbox'}
        ,{field:'tableName', title: '表名'}
        ,{field:'engine',  title: 'Engine', sort: true}
        ,{field:'tableComment',  title: '表备注'}
        ,{field:'createTime', title: '创建时间', minWidth: 100}
      ]]
      ,page: true
      ,height: 'full-250' //高度最大化减去差值
    });

    // 默认先读取到弹窗的html，避免多次点击重复加载
    var formHtml;
    $.ajax({
      url: "./views/genConfigForm.html",
      async: false,
      type: "GET",
      dataType: "html",
      success: function(result){
        formHtml = result;
      }
    })

    var defaultConfig;
    admin.req({
      type: "GET",
      url: "/generator/config",
      async: false,
      success: function (res) {
        defaultConfig = res.data;
      }
    });


    var active = {
      reload: function(){
        var tableName = $('#tableName');
        //执行重载
        table.reload(TABLE_ID, {
          page: {
            curr: 1 //重新从第 1 页开始
          }
          ,where: {
            tableName: tableName.val()
          }
        });
      },
      codegen: function(){

        var selected = table.checkStatus(TABLE_ID)
        ,data = selected.data;

        if(data == null || data.length === 0){
          layer.msg('请至少选择一条数据', {icon: 2});
          return;
        }

        var tableNames = [];

        for (var i = 0; i < data.length; i++) {
          tableNames.push(data[i].tableName);
        }

        layer.open({
          id: "genConfigLayer",
          type: 1,
          area: ['420px', '350px'],
          content: formHtml,
          btn: ['生成', '取消'],
          success: function() {
            form.val("gen-config-form", defaultConfig);
          },
          yes: function(index, layero){
            // 异步下载
            active.download(tableNames, form.val("gen-config-form"));
            // 关闭弹窗
            layer.close(index)
          }
        })

      },
      download: function (tableNames, genConfig) {
        var url = 'generator/code';
        var xhr = new XMLHttpRequest();
        // 也可以使用GET方式，根据接口
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-type','application/json');
        xhr.responseType = "blob";  // 返回类型blob
        // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
        xhr.onload = function () {
          // 请求完成
          if (this.status === 200) {
            // 返回200
            var blob = this.response;
            var reader = new FileReader();
            reader.readAsDataURL(blob);  // 转换为base64，可以直接放入a表情href
            reader.onload = function (e) {
              // 转换完成，创建一个a标签用于下载
              var a = document.createElement('a');
              a.download = 'BallCat.zip';
              a.href = e.target.result;
              $("body").append(a);  // 修复firefox中无法触发click
              a.click();
              $(a).remove();
            }
          }
        };
        // 发送ajax请求
        xhr.send(JSON.stringify({tableNames: tableNames, genConfigVO: genConfig}));
      }
    };
    
    $('.table-btn .layui-btn').on('click', function(){
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });
  
  });


    

  </script>