<template>
  <div class="page">
    <LayoutTable
      :data="tableData"
      :config="tableConfig"
      notSearch
      notAdd
      notDel
    >
      <Breadcrumb slot="breadcrumb" :list="breadcrumbList"></Breadcrumb>
      <el-button
        slot="table-head-left2"
        type="primary"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleGenTable"
        >生成代码</el-button
      >

      <el-button
        slot="table-head-left2"
        type="info"
        plain
        icon="el-icon-upload"
        size="mini"
        @click="openImportTable"
        >导入</el-button
      >

      <el-button
        slot="table-head-left2"
        type="danger"
        plain
        icon="el-icon-delete"
        size="mini"
        :disabled="multiple"
        @click="handleDelete"
        >删除</el-button
      >

      <el-button
        slot="table-head-left2"
        type="danger"
        plain
        icon="el-icon-upload"
        size="mini"
        @click="handleImportExcel"
        >导入文档</el-button
      >

      <el-button
        slot="table-head-left2"
        type="primary"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleGenDoc"
        >生成文档</el-button
      >

      <el-button
        slot="table-head-left2"
        type="primary"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleCreateTable"
        >执行建表语句</el-button
      >

      <!-- <el-button
        slot="table-head-left2"
        type="primary"
        plain
        icon="el-icon-download"
        size="mini"
        @click="test"
        >测试</el-button
      > -->
    </LayoutTable>
    <!-- 列表导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".doc, .docx"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“doc”或“docx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 预览界面 -->
    <el-dialog
      class="abow_dialog"
      :title="preview.title"
      :visible.sync="preview.open"
      width="90%"
      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('.ftl'))"
          :name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.ftl'))"
          :key="key"
        >
          <el-link
            :underline="false"
            type="primary"
            class="copy-btn"
            v-clipboard:copy="value"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            >复制</el-link
          >
          <pre><code  class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 文档导出对话框 -->
    <el-dialog
      :title="docExport.title"
      :visible.sync="docExport.open"
      width="600px"
      append-to-body
    >
      <el-form label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目名称">
              <el-input
                placeholder="请输入导出文档项目名称"
                v-model="docForm.platFormName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述信息">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入"
                v-model="docForm.tableComment"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDocExportForm">确 定</el-button>
        <el-button @click="docExport.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 建表对话框 -->
    <el-dialog
      :title="sqlDialog.title"
      :visible.sync="sqlDialog.open"
      width="1000px"
      append-to-body
    >
      <el-form label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="sql语句">
              <el-input
                type="textarea"
                :rows="15"
                placeholder="请输入建表DDL语句"
                v-model="sqlDialog.textarea"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSqlForm">确 定</el-button>
        <el-button @click="sqlDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 生成代码对话框 -->
    <el-dialog
      :title="genCodeDialog.title"
      :visible.sync="genCodeDialog.open"
      width="1000px"
      append-to-body
    >
      <el-form label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="生成代码类型">
              <el-checkbox true-label="1" false-label="0" v-model="all"
                >All</el-checkbox
              >

              <el-checkbox true-label="2" false-label="0" v-model="model"
                >model模型</el-checkbox
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGenCodeForm">确 定</el-button>
        <el-button @click="genCodeDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <import-table ref="import" @ok="handleQuery" />
  </div>
</template>

<script>
import importTable from "./importTable";
import table from "@/assets/mixins/table";
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("test", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("md", 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 {
  components: { importTable },
  mixins: [table],
  created() {
    const appId = this.$route.query["query.appId"];
    console.log("appId", appId);
    this.appId = appId;
    //this.query={ appId: appId }
    // this.config.addQuery = { appId: appId };
  },
  methods: {
    onCopy(e) {
      this.$message.success("内容已复制到剪切板！");
    },
    // 复制失败时的回调函数
    onError(e) {
      this.$message.error("抱歉，复制失败！");
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show(this.appId);
    },
    handleGenDoc() {
      this.docExport.title = "导出文档";
      this.docExport.open = true;
    },
    handleCreateTable() {
      this.sqlDialog.open = true;
    },
    /** 生成选中的文档 */
    submitDocExportForm() {
      const tableIds = this.ids;
      this.loading = true;
      let parms = Object.assign({}, this.docForm, {
        tables: tableIds.join(","),
      });
      this.$download("/gentable/exportDoc", parms, { type: "doc" })
        .then((res) => {
          this.loading = false;
          this.docExport.open = false;
        })
        .catch((error) => {
          console.log("error", error);
          this.$message.error(error.message);
        });
    },

    /** 生成sql建表 */
    submitSqlForm() {
      this.loading = true;
      this.$post("/device/liset", {
        tableSql: this.sqlDialog.textarea,
      })
        .then((res) => {

          this.loading = false;
          this.sqlDialog.open = false;
          this.sqlDialog.textarea = "";
          this.$message.success("执行成功！");
        })
        .catch((error) => {
          console.log("error", error);
          this.$message.error(error.message);
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getData();
      //this.queryParams.pageNum = 1;
      //this.getList();
    },
    submitGenCodeForm() {

      let types=[]
      types.push(this.all)
      types.push(this.model)
      let gentype=types.join(",")

      this.loading = true;
      if (this.genCodeDialog.tableName) {
      
        this.$download(
          "/gentable/genCode",
          {
            tableId: this.genCodeDialog.tableId,genTypes:gentype
          },
          { type: "zip" }
        )
          .then((res) => {
            this.loading = false;
          })
          .catch((error) => {
            console.log("error", error);
            this.$message.error(error.message);
          });
      } else {
        this.$download(
          "/gentable/batchGenCode",
          { tables: this.ids.join(",") ,genTypes:gentype},
          { type: "zip" }
        )
          .then((res) => {
            this.loading = false;
            this.genCodeDialog.open = false;
          })
          .catch((error) => {
            console.log("error", error);
            this.$message.error(error.message);
          });
      }
    },
    /** 生成代码操作 */
    handleGenTable(row) {
      console.log("gen", row);
      const tableIds = row.id || this.ids;
      if (tableIds == "") {
        this.$message.error("请选择要生成的数据");
        return;
      }

      if (row.tableName) {
        this.genCodeDialog.tableId = tableIds;
        this.genCodeDialog.tableName = true;
      } else {
        this.genCodeDialog.tableName = false;
      }

      this.genCodeDialog.open = true;
    },
    /** 同步数据库操作 */
    handleSynchDb(row) {
      let _this = this;
      this.$confirm('确认要强制同步"' + row.tableName + '"表结构吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        _this.loading = true;
        _this
          .$post("/gentable/synchDb", {
            tableId: row.id,
          })
          .then((res) => {
            if (res && res.code && res.code == 1) {
              _this.$message.success("同步成功");
            }
            _this.loading = false;
          })
          .catch((error) => {
            _this.$message.error(error.message);
          });
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 预览按钮 */
    handlePreview(row) {
      this.loading = true;
      this.$post("/gentable/preview", {
        id: row.id,
      })
        .then((res) => {
          this.preview.data = res.data;
          this.preview.open = true;
          this.loading = false;
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    /** 高亮显示 */
    highlightedCode(code, key) {
      const vmName = key.substring(
        key.lastIndexOf("/") + 1,
        key.indexOf(".ftl")
      );
      var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
      console.log("name", vmName, language);
      const result = hljs.highlight(language, code || "", true);
      return result.value || "&nbsp;";
    },
    //多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection.map((i) => i.id);
      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.$router.push({
        path: "/gen/edit",
        query: { tableId: tableId, appId: this.appId },
      });

      // this.$router.push("/gen/edit/" + tableId);
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      let _this = this;
      const tableIds = row.id || this.selection;
      this.$confirm('是否确认删除表编号为"' + tableIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          _this.toDel(tableIds, true);
        })
        .then(() => {
          this.getList();
        });
    },
    handleImportExcel() {
      this.upload.title = "导入";
      this.upload.url += this.appId;
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getData();
    },
    // 提交上传文件
    submitFileForm() {
      console.log(1111);
      this.$refs.upload.submit();
    },
  },
  data() {
    return {
      query: {
                pageInfo: {
                    prePageResult: 100
                }
            },
      breadcrumbList: [
        { name: "工程构建" },
        { name: "应用信息", path: "/app/list" },
        { name: "生成列表" },
      ],
      appId: null,
      all:"1",
      model:"0",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入文档",
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: "/m/gentable/importDoc?appId=",
      },
      // 文档导出参数
      docExport: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入文档",
        // 是否禁用上传
        isUploading: false,
      },
      sqlDialog: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "建表对话框",
        // 是否禁用上传
        textarea: "",
      },
      genCodeDialog: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "生成代码对话框",

        tableName: false,
      },
      // 预览参数
      preview: {
        open: false,
        title: "代码预览",
        data: {},
        activeName: "vo.java",
      },
      docForm: {},
      appId: null,

      config: {
        search: [],
        

        columns: [
          { type: "selection", width: 60 },

          { label: "表名称", prop: "tableName", width: 200 },
          { label: "表描述", prop: "tableComment" },
          { label: "关联子表的表名", prop: "subTableName" },
          { label: "子表关联的外键", prop: "subTableFkName" },
          { label: "实体类名称", prop: "className", width: 200 },
          { label: "生成包路径", prop: "packageName" },
          { label: "生成代码方式", prop: "genType", formatter: this.formatter },
          {
            label: "创建时间",
            prop: "createTime",
            formatter: this.formatterDate,
          },
          {
            label: "操作",
            width: 320,
            formatter: (row) => {
              return (
                <div>
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-view"
                    onClick={() => {
                      this.handlePreview(row);
                    }}
                  >
                    预览
                  </el-button>

                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-edit"
                    onClick={() => {
                      this.handleEditTable(row);
                    }}
                  >
                    编辑
                  </el-button>

                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-delete"
                    onClick={() => {
                      this.handleDelete(row);
                    }}
                  >
                    删除
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-refresh"
                    onClick={() => {
                      this.handleSynchDb(row);
                    }}
                  >
                    同步
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-download"
                    onClick={() => {
                      this.handleGenTable(row);
                    }}
                  >
                    生成代码
                  </el-button>
                </div>
              );
            },
          },
        ],
      },
    };
  },
};
</script>


<style lang="scss" scoped>
</style>


