<template>
  <div>
    <el-button style="margin-top:10px" @click="genEntrty">生成实体类</el-button>
    <el-button style="margin-top:10px" @click="genControler">生成接口类</el-button>
    <el-table
      :data="tableData.ColumnList"
      :header-cell-style="headerStyle"
      border
      stripe
      fit
      style="width: 100%;margin-top: 25px;"
    >
      <el-table-column fixed prop="ColumnName" label="字段名" width="150"></el-table-column>
      <el-table-column prop="Description" min-width="200" label="说明"></el-table-column>
      <el-table-column prop="ColumnType" min-width="120" label="类型"></el-table-column>
      <el-table-column prop="CharMaxLength" min-width="60" label="长度"></el-table-column>
      <el-table-column prop="Nullable" align="center" label="不是 null"></el-table-column>
      <el-table-column prop="Default" min-width="260" label="默认值"></el-table-column>
    </el-table>
  </div>
</template>

<script>
import Vue from "vue";
import ElementUI from "element-ui";
import Axios from "axios";
import "element-ui/lib/theme-chalk/index.css";
import Opt from "../opt";
import { SStringBuilder } from "@persagy-web/base";
Vue.use(ElementUI);

export default {
  data: function() {
    return {
      tableData: [],
      headerStyle: {
        backgroundColor: "#e1e4e5",
        color: "#2b2b2b",
        lineHeight: "30px"
      }, // 列表样式
      urlObj: {} // 路径参数
    };
  },
  components: {},
  created: function() {
    this.getData();
  },
  mounted: function() {
  },
  props: ["sys", "schema", "table","tableName"],
  computed: {},
  methods: {
    getData() {
      const origin = Location.origin
      Axios.get(
        `/${this.sys}/--database-doc--/table-info?schema=${
          this.schema
        }&table=${this.table}`,
        {}
      ).then(res => {
        this.tableData = res.data;
      });
    },
    //生成实体类
    genEntrty() {
      this.getUrlData();
      let strBuild = new SStringBuilder();
      const table = this.toHump(this.table);
      strBuild.append(
        `package cn.sagacloud.server.datacenter.models.entities

import cn.sagacloud.server.datacenter.models.entities.base.BaseInfo
import cn.sagacloud.server.datacenter.models.entities.task.SchemeUtils
import com.alibaba.fastjson.annotation.JSONField
import com.sybotan.service.models.annotations.SCascade
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
import javax.persistence.Column
import javax.persistence.Id
import javax.persistence.Table

/**
 * ${this.tableName}信息实体类
 *
 * @author  自动生成
 */
@ApiModel(description = "资产信息实体类")
@Table(name = "${this.schema}.${this.table}")
open class ${table} : BaseInfo(),Comparator<${table}> {
`
      );
      this.tableData.ColumnList.forEach(element => {
        strBuild.append(`    /** ${element.Description} */`);
        if (element.Nullable == "YES") {
          strBuild.append(
            `    @ApiModelProperty(value = "${element.Description}")`
          );
        } else {
          strBuild.append(
            `    @ApiModelProperty(value = "${element.Description}", required = true)`
          );
        }
        strBuild.append(`    @Column(name = "${element.ColumnName}")`);
        strBuild.append(
          `    var ${this.toSmallHump(element.ColumnName)}: ${this.typeToName(
            element.ColumnType
          )}? = null\n`
        );
      });

      strBuild.append(`} // Class ${table}`);
      this.download(`${table}.kt`, strBuild.toString());
    },

    //生成接口类
    genControler() {
      this.getUrlData();
      let strBuild = new SStringBuilder();
      const className = `${this.toHump(this.table)}Controller`;
      strBuild.append(`package cn.sagacloud.server.datacenter.controllers

import cn.sagacloud.server.datacenter.models.entities.Property
import cn.sagacloud.server.datacenter.services.PropertyService
import com.sybotan.base.extensions.toJson
import com.sybotan.database.SFilter
import com.sybotan.service.SPageContext
import com.sybotan.service.models.requests.SCountRequest
import com.sybotan.service.models.requests.SCreateRequest
import com.sybotan.service.models.requests.SQueryRequest
import com.sybotan.service.models.requests.SUpdateRequest
import com.sybotan.service.models.responses.SBaseResponse
import com.sybotan.service.models.responses.SCountResponse
import com.sybotan.service.models.responses.SCreateResponse
import com.sybotan.service.models.responses.SQueryResponse
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController


/**
 * ${this.tableName}接口
 *
 * @author 自动生成
 */
@Api(tags = ["${this.tableName}"])
@RestController
@RequestMapping("/object/${this.table}")
open class ${className} {
    companion object {
        /** 日志 */
        private val logger = LoggerFactory.getLogger(${className}::class.java)
    } // Companion object

     /**
     * 创建${this.tableName}
     *
     * @param   request        ${this.tableName}对象列表
     * @return                      创建结果信息
     */
    @ApiOperation(value = "创建${this.tableName}信息", notes = "")
    @PostMapping(value = ["/create"])
    fun create(@RequestBody request: SCreateRequest<${this.toHump(
      this.table
    )}>): SCreateResponse<${this.toHump(this.table)}> {

        return PropertyService.createList( request)
    } // Function create()

    /**
     * 根据id删除${this.tableName}
     *
     * @param   idList      id数组
     * @return              删除的结果信息
     */
    @ApiOperation(value = "根据id删除${this.tableName}信息", notes = "")
    @PostMapping(value = ["/delete"])
    fun delete(@RequestBody idList: ArrayList<${this.toHump(
      this.table
    )}>): SBaseResponse {
        return PropertyService.deleteByKeysList(idList)
    } // Function delete()

    /**
     * 更新${this.tableName}信息
     *
     * @param   request     更新的内容对象
     * @return              更新的结果
     */
    @ApiOperation(value = "更新${this.tableName}信息", notes = "")
    @PostMapping(value = ["/update"])
    fun update(@RequestBody request: SUpdateRequest<${this.toHump(
      this.table
    )}>): SBaseResponse {
        return PropertyService.updateList(request)
    } // Function update()

    /**
     * 查询${this.tableName}信息
     *
     * @param   request     查询信息条件
     * @return              查询结果
     */
    @ApiOperation(value = "查询${this.tableName}信息", notes="")
    @PostMapping(value = ["/query"])
    fun query(@RequestBody request: SQueryRequest): SQueryResponse<${this.toHump(
      this.table
    )}> {
        return PropertyService.pageQuery(request)
    } // Function query()

    /**
     * 根据条件查询统计数量
     */
    @ApiOperation(value = "根据条件查询统计数量", notes = "")
    @PostMapping(value = ["/count"])
    fun count(@RequestBody request: SCountRequest): SCountResponse {
        return PropertyService.count(request)
    } // Function count()
    `);
      strBuild.append(`} // Class ${className}`);
        this.download(`${className}.kt`, strBuild.toString());
    },
    // 数据包类型到实体类的转换
    typeToName(name) {
      const obj = {
        varchar: "String",
        char: "String",
        timestamptz: "Date",
        timestamp: "Date",
        text: "String",
        bool: "Boolean",
        int4: "Int",
        date: "Date",
        int2: "Int",
        json: "HashMap<String, Any?>",
        jsonb: "HashMap<String, Any?>"
      };
      if (name) {
        return obj[name] ? obj[name] : "String";
      } else {
        return "String";
      }
    },
    //转大驼峰
    toHump(str) {
      var arr = str.split("_");
      for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
      }
      return arr.join("");
    },
    //转小驼峰
    toSmallHump(str) {
      var arr = str.split("_");
      for (var i = 1; i < arr.length; i++) {
        arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
      }
      return arr.join("");
    },
    // 获取路径名称以及路径type
    getUrlData() {
      const dataArr = Location.href.split("#")[1].split("-");
      let obj = {};
      if (dataArr.length == 2) {
        obj = {
          urlType: dataArr[1],
          urlName: decodeURIComponent(dataArr[0])
        };
      } else {
        let urlName = "";
        let lengthNum = dataArr.length;
        dataArr.forEach((item, i) => {
          if (i + 2 <= lengthNum) {
            urlName = urlName + "-" + item;
          }
        });
        obj = {
          urlType: dataArr[lengthNum-1],
          urlName: decodeURIComponent(urlName)
        };
      }

      this.urlObj = obj;
    },
    // 下载文件
    download(filename, text) {
      var element = document.createElement("a");
      element.setAttribute(
        "href",
        "data:text/plain;charset=utf-8," + encodeURIComponent(text)
      );
      element.setAttribute("download", filename);

      element.style.display = "none";
      document.body.appendChild(element);

      element.click();

      document.body.removeChild(element);
    }
  }
};
</script>

<style scoped>
/deep/ table {
  margin: 0;
}
</style>
