<template>
  <div>
    <a-row class="headerRow">
      <a-select
        v-model="dataSourceId"
        filterable
        allow-clear
        style="width: 200px"
        :placeholder="$t('PLACESELECT')"
      >
        <a-select-option
          v-for="item in dataSourceIdList"
          :key="item.id"
          :value="item.id"
        >
          {{ item.dataSourceName }}
        </a-select-option>
      </a-select>
      <a-button class="flxBtn" @click="handSql">
        <a-icon type="caret-right" class="iconGreen" />
        {{ $t("EXECUTIVE") }}
      </a-button>
      <a-button @click="formaterSql(basicInfoForm.sqlMain)">
        <Icon type="icon-cur-t-meihua" :size="16" />
        {{ $t("SQL_ESTHETIC") }}
      </a-button>
      <a-button @click="handReset">
        <a-icon type="reload" />{{ $t("RESET") }}
      </a-button>
    </a-row>
    <SqlEditor
      ref="sqleditor"
      :value="basicInfoForm.sqlMain"
      @changeTextarea="changeTextarea($event)"
    />
    <a-tabs v-model="tabsSelect" type="card">
      <a-tab-pane key="1" :tab="$t('INFORMATION')">
        <div style="padding-left: 20px">
          <p v-if="cost">{{ basicInfoForm.sqlMain }}</p>
          <p v-if="cost">> {{ $t("TIME") }}：{{ cost }}s</p>
        </div>
      </a-tab-pane>
      <a-tab-pane v-if="fields != null" key="2" :tab="$t('RESULT')">
        <div v-if="tableColumnsList.length > 0" class="rulesStr">
          <MomTable
            ref="MomTable"
            row-key="ID"
            :columns="tableColumnsList"
            :data-source="tableDataList"
            :mega-extend="{ rowIndex: false, rowAction: false }"
          >
          </MomTable>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script>
import { format } from "sql-formatter";
import { Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import SqlEditor from "@/components/SqlEditor";

export default {
  components: {
    SqlEditor,
    Icon,
  },
  data() {
    return {
      tabsSelect: "2", // 默认显示的tabs
      cost: "", // 时间
      fields: null,
      dataSourceId: "", // 查询数据源id
      basicInfoForm: {
        // sql语句
        sqlMain: "",
      },
      tableDataList: [], // 表格数据
      tableColumnsList: [], // 表格列数据
      dataSourceIdList: [], // 数据源下拉数据
    };
  },
  created() {
    if (this.$route.query.id) {
      this.dataSourceId = this.$route.query.id;
    }
    this.$axios.get(`/core/api/sys/datasource/list`).then((res) => {
      this.dataSourceIdList = res.data.data;
    });
  },
  methods: {
    changeTextarea(val) {
      this.$set(this.basicInfoForm, "sqlMain", val);
    },
    handSql() {
      if (this.basicInfoForm.sqlMain) {
        const str = this.basicInfoForm.sqlMain.toLowerCase();
        if (str.substr(0, 6) === "select") {
          this.excuteSql();
        } else {
          this.$confirm({
            title: this.$t("TIPS"),
            content: this.$t("SQL_ERROR"),
            okType: "warning",
            okText: this.$t("CONFIRM"),
            cancelText: this.$t("CANCEL"),
            centered: false,
            icon: "exclamation-circle",
            onOk: () => {
              this.excuteSql();
            },
          });
        }
      }
    },
    excuteSql() {
      const params = {
        dataSourceId: this.dataSourceId,
        querySql: this.basicInfoForm.sqlMain,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource-query/excute-sql`, {
          params,
        })
        .then((res) => {
          this.tableColumnsList = [];
          this.cost = res.data.data.cost / 1000;
          this.fields = res.data.data.fields;
          this.tabsSelect = this.fields != null ? "2" : "1";
          if (
            res.data.data.fields != null &&
            res.data.data?.fields.length > 0
          ) {
            this.tableDataList = res.data.data.result;
            res.data.data?.fields.forEach((item) => {
              this.tableColumnsList.push({
                dataIndex: item,
                title: item,
                width: 160,
                ellipsis: true,
                sorter: false,
              });
            });
          }
        });
    },
    formaterSql(val) {
      // eslint-disable-next-line global-require
      const dom = this.$refs.sqleditor;
      dom.editor.setValue(format(val));
    },
    // 清空
    handReset() {
      const dom = this.$refs.sqleditor;
      dom.editor.setValue(format(""));
      this.tableDataList = [];
      this.tableColumnsList = [];
      this.cost = "";
    },
  },
};
</script>
<style lang="less" scoped>
.rulesStr {
  /deep/.s-table-tool {
    display: none;
  }
}
.headerRow {
  width: 100%;
  background: #f0f2f5;
  padding-bottom: 5px;
  display: flex;
}
.flxBtn {
  display: flex;
  justify-content: center;
  align-items: center;
}
.iconGreen {
  color: #61c22c;
  font-size: 25px;
}
</style>
