<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-plus" size="mini" @click="handleGenTableadd">新增</el-button>
        <!-- v-hasPermi="['tool:gen:code']" -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleGenTable" v-hasPermi="['tool:gen:code']">生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="openImportTable" v-hasPermi="['tool:gen:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleEditTable"
          v-hasPermi="['tool:gen:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['tool:gen:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-refresh" size="mini" style="background-color: #FDD6F3;color: #C790B9;border: 1px solid #C790B9;"
          @click="handleCxbtn" v-hasPermi="['tool:gen:remove']">重载缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表名称" prop="tableName">
        <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input v-model="queryParams.tableComment" placeholder="请输入表描述" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
   <transition
     mode="out-in"
     @before-enter="beforeEnter"
     @enter="enter"

     @before-leave="beforeLeave"
     @leave="leave"
     :css="false">

   </transition>

    <!-- style="max-height: calc(100vh - 288px);overflow-y: auto;" -->
    <el-table v-loading="loading" height="400" :data="tableList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="表名称" align="center" prop="tableName" :show-overflow-tooltip="true" />
      <el-table-column label="表描述" align="center" prop="tableComment" :show-overflow-tooltip="true" />
      <el-table-column label="实际数据库表" align="center" prop="realTableName" :show-overflow-tooltip="true" />
      <el-table-column label="是否菜单" align="center">
        <template slot-scope="scope">
          <el-checkbox true-label="Y" false-label="N" v-model="scope.row.isMenu"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="菜单权限" align="center" prop="menuRole" />
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="更新时间" align="center" prop="updateTime" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
            v-hasPermi="['tool:gen:preview']"
          >预览</el-button> -->
          <el-button type="text" size="small" icon="el-icon-edit" @click="handleEditTable(scope.row)" v-hasPermi="['tool:gen:edit']">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['tool:gen:remove']">删除</el-button>
          <el-button type="text" size="small" icon="el-icon-refresh" @click="handleSynchDb(scope.row)" v-hasPermi="['tool:gen:edit']">同步</el-button>
          <!--          <el-button
            type="text"
            size="small"
            icon="el-icon-download"
            @click="handleGenTable(scope.row)"
            v-hasPermi="['tool:gen:code']"
          >生成代码</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 新增弹框 -->
    <el-dialog :close-on-click-modal="false" :title="preview.title" :visible.sync="preview.open" width="65%" top="5vh"
      append-to-body>
      <!-- <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :key="key"
        >
        <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs> -->
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="表名称" prop="tableName">
              <el-input v-model="form.tableName" placeholder="请输入表名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际数据库表" prop="className">
              <el-input v-model="form.className" placeholder="请输入实际数据库表" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="表描述" prop="tableComment">
              <el-input v-model="form.tableComment" placeholder="请输入表描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否菜单">
              <el-radio-group v-model="form.isMenu">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="列数" prop="tableColumn">
              <el-input type="number" :max="4" :min="1" v-model="form.tableColumn" placeholder="请输入列数" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单权限" prop="menuRole">
             <!-- <el-input v-model="form.menuRole" placeholder="请输入菜单权限" /> -->
             <el-select  v-model="jeg" :multiple ="true" clearable placeholder="请选择菜单权限" @visible-change = "visiblechange" @change="changetr" @blur="blurkde" filterable>
                <div style="margin-left: 20px;">
                  <!-- <el-checkbox v-model="checked" @change="checkedAll"/> 全选/反选 -->
                </div>
                 <el-option
                   ref="tree"
                   v-for="item in userList"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value">
                 </el-option>
               </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新增程序" prop="triggerCreate">
              <el-input v-model="form.triggerCreate" placeholder="请输入新增程序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检索程序" prop="triggerRetrieve">
              <el-input v-model="form.triggerRetrieve" placeholder="请输入检索程序" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微改程序" prop="triggerUpdate">
              <el-input v-model="form.triggerUpdate" placeholder="请输入微改程序" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="删除程序" prop="triggerDelete">
              <el-input v-model="form.triggerDelete" placeholder="请输入删除程序" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交程序" prop="triggerSubmit">
              <el-input v-model="form.triggerSubmit" placeholder="请输入提交程序" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过滤条件" prop="filterConditions">
              <el-input v-model="form.filterConditions" placeholder="请输入过滤条件" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展属性" prop="extendedAttributes">
              <el-input v-model="form.extendedAttributes" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <import-table ref="import" @ok="handleQuery" />
  </div>
</template>

<script>
  import {
    listTable,
    previewTable,
    delTable,
    genCode,
    synchDb,
    addMenu,
    getLoadTable
  } from "@/api/tool/gen";
  import importTable from "./importTable";
  import {
    downLoadZip
  } from "@/utils/zipdownload";
  import hljs from "highlight.js/lib/highlight";
  import "highlight.js/styles/github-gist.css";
  hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
  hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
  hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
  hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
  hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
  hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));

  export default {
    name: "Gen",
    components: {
      importTable
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 唯一标识符
        uniqueId: "",
        // 选中数组
        ids: [],
        // 选中表数组
        tableNames: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表数据
        tableList: [],
        // 日期范围
        dateRange: "",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          tableName: undefined,
          tableComment: undefined
        },
        // 预览参数
        preview: {
          open: false,
          title: "代码预览",
          data: {},
          activeName: "domain.java"
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          tableName: [{
            required: true,
            message: "表名称不能为空",
            trigger: "blur"
          }],
          tableComment: [{
            required: true,
            message: "表描述不能为空",
            trigger: "blur"
          }],
          menuRole: [{
            required: true,
            message: "菜单权限不能为空",
            trigger: "blur"
          }],
          tableColumn: [{
            required: true,
            message: "列数不能为空",
            trigger: "blur"
          }]
        },
        userList:[{
          value: 'A',
          label: 'A:新增'
        },
        {
          value: 'M',
          label: 'M:修改'
        },
        {
          value: 'D',
          label: 'D:删除'
        },
        {
          value: 'S',
          label: 'S:提交'
        },{
          value: 'Q',
          label: 'Q:查询'
        },{
          value: 'U',
          label: 'U:反提交'
        }],
        jeg:''
      };
    },
    created() {
      this.getList();
    },
    activated() {
      const time = this.$route.query.t;
      if (time != null && time != this.uniqueId) {
        this.uniqueId = time;
        this.resetQuery();
      }
    },
    methods: {
      handleCxbtn() {
        getLoadTable().then(res => {
          this.msgSuccess('重载缓存成功')
        })
      },
      /** 查询表集合 */
      getList() {
        this.loading = true;
        listTable(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.tableList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 生成代码操作 */
      handleGenTable(row) {
        const tableNames = row.tableName || this.tableNames;
        if (tableNames == "") {
          this.msgError("请选择要生成的数据");
          return;
        }
        if (row.genType === "1") {
          genCode(row.tableName).then(response => {
            this.msgSuccess("成功生成到自定义路径：" + row.genPath);
          });
        } else {
          downLoadZip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
        }
      },
      /** 同步数据库操作 */
      handleSynchDb(row) {
        const tableName = row.tableName;
        this.$confirm('确认要强制同步"' + tableName + '"表结构吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return synchDb(tableName);
        }).then(() => {
          this.msgSuccess("同步成功");
        })
      },
      /** 打开导入表弹窗 */
      openImportTable() {
        this.$refs.import.show();
      },
      // 表单重置
      reset() {
        this.form = {

        };
        this.resetForm("form");
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 预览按钮 */
      handlePreview(row) {
        previewTable(row.tableId).then(response => {
          this.preview.data = response.data;
          this.preview.open = true;
        });
      },
      /** 高亮显示 */
      highlightedCode(code, key) {
        const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
        var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
        const result = hljs.highlight(language, code || "", true);
        return result.value || '&nbsp;';
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.tableNames = selection.map(item => item.tableName);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 修改按钮操作 */
      handleEditTable(row) {
        const tableId = row.id || this.ids[0];
        this.$router.push("/gen/edit/" + tableId);
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const tableIds = row.id || this.ids;
        this.$confirm('是否确认删除表编号为"' + tableIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTable(tableIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      // 取消弹框按钮
      cancel() {
        console.log(123)
        this.reset()
        this.preview.open = false;

      },
      //新增
      handleGenTableadd() {
        this.reset()
        this.preview.open = true;
        this.preview.title = '新增信息';
      },
      /** 提交按钮 */
      submitForm: function() {
        if( this.form.tableColumn > 4 ){
          this.msgSuccess("列数不能大于4");
          return false
        }else if(this.form.tableColumn <1){
          this.msgSuccess("列数不能小于1");
          return false
        }

        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              // updateMenu(this.form).then(response => {
              //   this.msgSuccess("修改成功");
              //   this.open = false;
              //   this.getList();
              // });
              console.log(23)
            } else {
              console.log(this.form)
              addMenu(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.preview.open = false;
                this.getList();
              });
            }
          }
        });
      },
      // 下拉框出现/隐藏时触发
      visiblechange(val){
       console.log(val)
      },
      changetr(val){
        console.log(val)
        let name = []
        let huej = []
        name = val.join('')
        // for(var i = 0 ; i <this.userList.length; i++ ){
        //   if(this.userList[i].userId == name[i]){

        //   }
        // }
        // var flag;
        // for (var i in name) {
        //   flag = true;
        //   for (var j in this.userList) {
        //     if (this.userList[j].userId == name[i]) {
        //       // flag = false;
        //       huej.push(this.userList[j])
        //       // break;
        //     }
        //   }
        //   // if (flag) {
        //   //   this.userList.push(name[i]);
        //   // }
        // }
        this.form.menuRole = name
        if(this.form.menuRole.length == 0){
          this.form.menuRole == undefined
        }
        // this.userList
        console.log(val)
        console.log(this.form.menuRole)
      },
      blurkde(){

      }
    }
  };
</script>
