<template>
  <el-card
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="basic">
        <basic-info-form ref="basicInfo" :info="info" />
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="cloum">
        <el-table
          ref="dragTable"
          :data="cloumns"
          row-key="columnId"
          :max-height="tableHeight"
        >
          <el-table-column
            label="序号"
            type="index"
            min-width="5%"
            class-name="allowDrag"
          />
          <el-table-column
            label="字段列名"
            prop="columnName"
            min-width="10%"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="字段描述" min-width="10%">
            <template slot-scope="scope">
              <el-input v-model="scope.row.columnComment"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="物理类型"
            prop="columnType"
            min-width="10%"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="Java类型" min-width="11%">
            <template slot-scope="scope">
              <el-select v-model="scope.row.javaType">
                <el-option label="Long" value="Long" />
                <el-option label="String" value="String" />
                <el-option label="Integer" value="Integer" />
                <el-option label="Double" value="Double" />
                <el-option label="BigDecimal" value="BigDecimal" />
                <el-option label="Date" value="Date" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="java属性" min-width="10%">
            <template slot-scope="scope">
              <el-input v-model="scope.row.javaField"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="插入" min-width="5%">
            <template slot-scope="scope">
              <el-checkbox
                true-label="1"
                v-model="scope.row.isInsert"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="编辑" min-width="5%">
            <template slot-scope="scope">
              <el-checkbox
                true-label="1"
                v-model="scope.row.isEdit"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="列表" min-width="5%">
            <template slot-scope="scope">
              <el-checkbox
                true-label="1"
                v-model="scope.row.isList"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="查询" min-width="5%">
            <template slot-scope="scope">
              <el-checkbox
                true-label="1"
                v-model="scope.row.isQuery"
              ></el-checkbox>
            </template>
          </el-table-column>

          <el-table-column label="必填" min-width="5%">
            <template slot-scope="scope">
              <el-checkbox
                true-label="1"
                v-model="scope.row.isRequired"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="显示类型" min-width="12%">
            <template slot-scope="scope">
              <el-select v-model="scope.row.htmlType">
                <el-option
                  v-for="(label, value) in dict.htmlType"
                  :key="value"
                  :label="label"
                  :value="value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="生成信息" name="genInfo">
        <gen-info-form
          ref="genInfo"
          :info="info"
          :dict="dict"
          :tables="tables"
          :menus="menus"
        />
      </el-tab-pane>
    </el-tabs>
    <el-form label-width="100px">
      <el-form-item
        style="text-align: center; margin-left: -100px; margin-top: 10px"
      >
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import basicInfoForm from "./basicInfoForm";
import genInfoForm from "./genInfoForm";
import Sortable from "sortablejs";

export default {
  name: "GenEdit",
  components: {
    basicInfoForm,
    genInfoForm,
  },
  data() {
    return {
      // 选中选项卡的 name
      activeName: "cloum",
      // 表格的高度
      tableHeight: 500 + "px",
      // 表信息
      tables: [],
      // 表列信息
      cloumns: [],
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      // 表详细信息
      info: {},
      dict: {},
      toString: [
        "isPrimaryKey",
        "isIncrement",
        "isRequired",
        "isInsert",
        "isEdit",
        "isList",
        "isQuery",
        "htmlType",
        "cacheServiceType",
        "dividedTableType",
        "genType",
      ], // 需要把number转化为string的表单字段name数组
    };
  },
  created() {
    const tableId = this.$route.query && this.$route.query.tableId;
    console.log("tableId", tableId);

    if (tableId) {
      this.loading = true;
      this.$post("/gentable/info", { tableId: tableId })
        .then((res) => {
          if (res && res.code && res.code == 1) {
            this.cloumns = res.data.rows.map((entity) =>
              this.util_toString(entity, this.toString)
            );
            this.info = this.util_toString(res.data.info, this.toString);
            this.tables = res.data.tables;
            this.dict = Object.assign({}, this.dict, res.data.dict);
            this.loading = false;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    }
  },
  methods: {
    /** 提交按钮 */
    submitForm() {
      const basicForm = this.$refs.basicInfo.$refs.basicInfoForm;
      const genForm = this.$refs.genInfo.$refs.genInfoForm;

      //console.log("basicForm", basicForm);
      //console.log("genForm", genForm);
      Promise.all([basicForm, genForm].map(this.getFormPromise)).then((res) => {
        const validateResult = res.every((item) => !!item);
        //console.log("validateResult", validateResult);
        if (validateResult) {
          const genTable = Object.assign({}, basicForm.model, genForm.model);
          genTable.columns = this.cloumns;
          this.loading = true;
          this.$post("/gentable/save", {
            entity: genTable,
          })
            .then((res) => {
              // 更新数据
              if (res.data.import) {
                this.$message.success(res.msg);
              } else {
                this.$message.success("更新成功");
              }
              this.close();
            })
            .catch((error) => {
              this.$message.error(error.message);
            })
            .then((data) => {
              clearTimeout(this.loadingTimer);
              this.loadingTimer = setTimeout(() => {
                this.loading = false;
              }, 300);
            });
        } else {
          this.$message.error("表单校验未通过，请重新检查提交内容");
        }
      });
    },
    getFormPromise(form) {
      console.log("数据校验");
      return new Promise((resolve) => {
        form.validate((res) => {
          resolve(res);
        });
      });
    },
    /** 关闭按钮 */
    close() {
      this.$router.go(-1);
    },
    // 工具方法，把数字转化为字符串
    util_toString(data, array) {
      const dataCopy = Object.assign({}, data);

      array.forEach((item) => {
        dataCopy[item] =
          dataCopy[item] === undefined ? "" : dataCopy[item] + "";
      });
      return dataCopy;
    },
  },
  mounted() {
    const el = this.$refs.dragTable.$el.querySelectorAll(
      ".el-table__body-wrapper > table > tbody"
    )[0];
    const sortable = Sortable.create(el, {
      handle: ".allowDrag",
      onEnd: (evt) => {
        const targetRow = this.cloumns.splice(evt.oldIndex, 1)[0];
        this.cloumns.splice(evt.newIndex, 0, targetRow);
        for (let index in this.cloumns) {
          this.cloumns[index].sort = parseInt(index) + 1;
        }
      },
    });
  },
};
</script>
