<template>
  <div class="height_100">
    <a-row class="height_100 row_col_show">
      <a-col :span="5" style="position: relative">
        <div class="table_title title_two">
          <span>
            {{ $t("DATA_SOURCE") }}
          </span>
          <div style="display: flex; align-items: center">
            <a-button type="text" class="button_left" @click="handSqlSearch">
              <Icon type="icon-cur-Console-SQL" :size="20" />
            </a-button>
            <a-button
              v-if="hasAuth('CORE:SYSTEM:TABLE:ADD')"
              type="text"
              class="button_left"
              @click="handleAdd"
            >
              <a-icon class="operation-icon icon-defult" type="plus-circle" />
            </a-button>
          </div>
        </div>
        <ul class="ul_data_show">
          <li
            v-for="(item, index) in tableData"
            :key="index"
            class="title_two"
            :class="rowBlue === item.id ? 'rowBlue' : ''"
            @click="getTableCenter(item)"
          >
            <div class="text_ellipsis">
              <Icon type="icon-cur-a-Datapush" :size="16" />
              {{ item.dataSourceName }}
            </div>
            <div class="botton_show_key">
              <a-button
                v-if="hasAuth('CORE:SYSTEM:TABLE:EDIT')"
                type="text"
                :style="
                  rowBlue === item.id
                    ? 'border: none; padding: 0; background: #dfeff7'
                    : 'border: none; padding: 0;'
                "
                @click="handleEdit(item, $event)"
              >
                <Icon class="text-primary" type="icon-edit-form" :size="16" />
              </a-button>
              <a-button
                type="text"
                :style="
                  rowBlue === item.id
                    ? 'border: none; padding: 0; background: #dfeff7'
                    : 'border: none; padding: 0;'
                "
                @click="handSqlSearch(item, $event)"
              >
                <Icon
                  class="text-primary"
                  type="icon-cur-Console-SQL"
                  :size="20"
                />
              </a-button>
              <a-button
                v-if="hasAuth('CORE:SYSTEM:TABLE:DELETE')"
                type="text"
                :style="
                  rowBlue === item.id
                    ? 'border: none; padding-left: 0; background: #dfeff7'
                    : 'border: none; padding-left: 0;'
                "
                @click="handleDelete(item, $event)"
              >
                <Icon class="text-error" type="icon-edit-delete" :size="20" />
              </a-button>
            </div>
          </li>
        </ul>
        <a-pagination
          small
          class="pagination_position"
          :current-page="queryForm.page"
          :pager-count="5"
          hide-on-single-page
          :page-size="pageSize"
          layout="sizes, prev, pager, next"
          :total="total"
          @size-change="sizeChange"
          @current-change="currentChange"
        />
      </a-col>
      <a-col :span="8" class="middlle_tabel">
        <div class="table_title title_two">
          {{ $t("TABLE_LIST") }}
          <a-input-search
            v-model="searchCenterKey"
            style="width: 200px"
            allow-clear
            :placeholder="$t('QUERY_TABLE_NAME')"
          />
        </div>
        <MomTable
          :columns="tableColumnsCenter"
          :data-source="tableDataCenterShow"
          :show-util-operator="false"
          :mega-extend="{ rowIndex: false, rowAction: false }"
          :pagination="false"
          :custom-row="rowClick"
          :row-class-name="setRowClassName"
        >
        </MomTable>
      </a-col>
      <a-col :span="11">
        <div class="table_title">
          {{ $t("FIELD_LIST") }}
        </div>
        <MomTable
          :columns="tableColumnsRight"
          :data-source="tableDataRight"
          :show-util-operator="false"
          :mega-extend="{ rowIndex: false, rowAction: false }"
          :pagination="false"
        >
          <template slot="isNullable" slot-scope="text, record">
            {{ formatData(whetherIntList, record.isNullable) }}
          </template>
        </MomTable>
      </a-col>
    </a-row>
    <MegaDrawer
      :visible.sync="drawerVisible"
      :title="drawerTitle"
      :wrapper-closable="false"
      append-to-body
      destroy-on-close
      width="520"
      @close="close"
    >
      <div slot="main">
        <a-form-model
          ref="dataSource"
          layout="vertical"
          :model="dataSource"
          :rules="rules"
        >
          <a-form-model-item :label="$t('TYPE')" prop="dataSourceType">
            <a-select
              v-model="dataSource.dataSourceType"
              filterable
              allow-clear
              :placeholder="$t('PLACESELECT')"
              @change="typeChange"
            >
              <a-select-option
                v-for="item in dataSourceTypeOptions"
                :key="item.desc"
                :value="item.desc"
              >
                {{ item.desc }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            :label="$t('DATA_SOURCE_NAME')"
            prop="dataSourceName"
          >
            <a-input
              v-model="dataSource.dataSourceName"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('DATA_SOURCE_GROUP')"
            prop="dataSourceGroup"
          >
            <a-input
              v-model="dataSource.dataSourceGroup"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('USER_NAME')" prop="jdbcUsername">
            <a-input
              v-model="dataSource.jdbcUsername"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('PASSWORD')" prop="jdbcPassword">
            <a-input
              v-model="dataSource.jdbcPassword"
              :placeholder="$t('PLACEENTER')"
              type="password"
            />
          </a-form-model-item>
          <a-form-model-item label="jdbc url" prop="jdbcUrl">
            <a-input
              v-model="dataSource.jdbcUrl"
              type="textarea"
              :placeholder="$t('PLACEENTER')"
              :rows="2"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item
            :label="`jdbc${$t('DRIVE_CLASS')}`"
            prop="jdbcDriverClass"
          >
            <a-select
              v-model="dataSource.jdbcDriverClass"
              filterable
              allow-clear
              :placeholder="$t('PLACESELECT')"
              @change="typeChange"
            >
              <a-select-option
                v-for="item in jdbcDriverClassOptions"
                :key="item"
                :value="item"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="$t('REMARK')" prop="comments">
            <a-input
              v-model="dataSource.comments"
              type="textarea"
              :placeholder="$t('PLACEENTER')"
              :rows="2"
              allow-clear
            />
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button
          v-if="hasAuth('CORE:SYSTEM:TABLE:CONNECT')"
          type="primary"
          @click="handleConnect"
        >
          <a-icon type="link" />
          {{ $t("TEST_CONNECT") }}
        </a-button>
        <a-button type="primary" @click="save">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="close">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaDrawer>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      searchCenterKey: "",
      rowBlue: "",
      getIndex: "",
      rowIndex: -1,
      isFixHeight: true,
      tableHeight: null,
      tableData: [],
      queryForm: {
        dataSourceName: "",
        dataSourceType: null,
        page: 1,
        size: 0,
      },
      sortParams: null,
      tableDataCenter: [],
      tableDataCenterShow: [],
      tableDataRight: [],
      total: 1,
      drawerVisible: false,
      drawerType: "add",
      passwordInput: false,
      dataSourceTypeOptions: [],
      dataSource: {
        id: null,
        dataSourceType: "",
        dataSourceName: "",
        dataSourceGroup: "Default",
        jdbcUsername: "",
        jdbcPassword: "",
        jdbcDriverClass: "",
        jdbcUrl: "",
        comments: "",
      },
      dataSourceIdList: [],
      whetherIntList: [],
      jdbcDriverClassOptions: [],
    };
  },
  computed: {
    ...mapState({
      pageSizes: (state) => state.pagination.pageSizes,
      pageSize: (state) => state.pagination.pageSize,
    }),
    realHeight() {
      if (this.isFixHeight) {
        return this.tableHeight;
      }
      return this.paramsHeight;
    },
    rules() {
      return {
        dataSourceType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        dataSourceName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        jdbcUrl: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    drawerTitle() {
      if (this.drawerType === "add") {
        return this.$t("ADD");
      }
      if (this.drawerType === "edit") {
        return this.$t("EDIT");
      }
      return "";
    },
    tableColumnsCenter() {
      return [
        {
          dataIndex: "tableName",
          title: () => this.$t("TABLE_NAME"),
          width: 220,
          sorter: (rowA, rowB) =>
            rowA.name
              .toUpperCase()
              .substr(0, 1)
              .localeCompare(rowB.name.toUpperCase().substr(0, 1)), // 按名称首字母排序
        },
        {
          dataIndex: "tableComment",
          title: () => this.$t("NOTE"),
          sorter: false,
          minWidth: 200,
        },
      ];
    },
    tableColumnsRight() {
      return [
        {
          dataIndex: "columnName",
          title: () => this.$t("FIELD_NAME"),
          width: 180,
          sorter: false,
        },
        {
          dataIndex: "dataType",
          title: () => this.$t("TYPE"),
          sorter: false,
          width: 100,
        },
        {
          dataIndex: "length",
          title: () => this.$t("LENGTH"),
          width: 100,
          sorter: false,
        },
        {
          dataIndex: "isNullable",
          title: () => this.$t("ALLOW_TO_BE_EMPTY"),
          width: 100,
          sorter: false,
          scopedSlots: { customRender: "isNullable" },
        },
        {
          dataIndex: "columnComment",
          title: () => this.$t("NOTE"),
          sorter: false,
          minWidth: 200,
        },
      ];
    },
  },
  watch: {
    searchCenterKey(newValue, oldValue) {
      if (newValue === "") {
        this.tableDataCenterShow = this.tableDataCenter;
      } else {
        this.tableDataCenterShow = this.tableDataCenter.filter((v) =>
          v.tableName.includes(newValue)
        );
      }
    },
  },
  created() {
    this.queryForm.size = this.pageSize;
    this.searchPageData();
    this.$axios
      .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/types`)
      .then((res) => {
        this.dataSourceTypeOptions = res.data.data;
      });
    this.getDictByCode("DIC:COMMON:WHETHER_INT").then((res) => {
      this.whetherIntList = res.data.data;
    });
  },
  methods: {
    handSqlSearch(row, e) {
      if (row.id) {
        e.stopPropagation();
        this.$router.push({
          path: "/upms/system/setting/tableManage/search",
          query: {
            id: row.id,
          },
        });
      } else {
        this.$router.push({
          path: "/upms/system/setting/tableManage/search",
        });
      }
    },
    // 格式化数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    rowClick(record, index) {
      return {
        on: {
          click: () => {
            this.rowIndex = index;
            this.getTableRight(record);
          },
        },
      };
    },
    // eslint-disable-next-line consistent-return
    selectedstyle({ row, rowIndex }) {
      if (this.getIndex === rowIndex) {
        return {
          "background-color": "#3dc2e5!important",
          height: "40px",
        };
      }
    },
    // 表清单排序
    sortTableCenter(data) {
      if (data.sortRule === "DESC") {
        this.tableDataCenterShow = this.tableDataCenterShow.sort((a, b) =>
          a[data.sortColumn].localeCompare(b[data.sortColumn])
        );
      } else {
        this.tableDataCenterShow = this.tableDataCenterShow.sort((a, b) =>
          b[data.sortColumn].localeCompare(a[data.sortColumn])
        );
      }
    },
    // 获取表清单
    getTableCenter(row) {
      this.tableDataCenter = [];
      this.tableDataRight = [];
      this.searchCenterKey = "";
      this.rowBlue = row.id;
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/datasource-query/table-infos`,
          {
            params: { dataSourceId: row.id },
          }
        )
        .then((res) => {
          this.tableDataCenter = res.data.data;
          // eslint-disable-next-line no-param-reassign
          this.tableDataCenter.map((v) => (v.dataSourceId = row.id));
          this.tableDataCenterShow = this.tableDataCenter;
        });
    },
    // 获取字段清单
    getTableRight(row) {
      this.tableDataRight = [];
      this.getIndex = row.rowIndex;
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/datasource-query/column-infos`,
          {
            params: {
              dataSourceId: row.dataSourceId,
              tableName: row.tableName,
            },
          }
        )
        .then((res) => {
          this.tableDataRight = res.data.data;
        });
    },
    // 分页回调 页码
    currentChange(callback) {
      this.queryForm.page = callback;
      this.searchPageData();
    },
    // 分页回调 页数
    sizeChange(callback) {
      this.queryForm.size = callback;
      this.queryForm.page = 1;
      this.searchPageData();
    },
    /**
     * 点击行数据
     */
    handleAdd() {
      this.drawerType = "add";
      this.$set(this, "dataSource", {
        id: null,
        dataSourceType: "",
        dataSourceName: "",
        dataSourceGroup: "Default",
        jdbcUsername: "",
        jdbcPassword: "",
        jdbcDriverClass: "",
        jdbcUrl: "",
        comments: "",
      });
      this.drawerVisible = true;
    },
    searchPageData() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/search`, {
          params: {
            ...this.queryForm,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = Number(res.data.data.total);
          // this.tableDataCenter = []
          // this.tableDataRight = []
        });
    },
    // 展示密码 之后的修改按钮
    passwordInputHandle() {
      this.passwordInput = true;
      this.dataSource.databasePassword = null;
    },
    typeChange(value) {
      const obj = this.dataSourceTypeOptions.find(
        (item) => item.desc === value
      );
      if (obj) {
        this.dataSource.jdbcUrl = obj.url;
        this.jdbcDriverClassOptions = obj.driver;
        // eslint-disable-next-line prefer-destructuring
        obj.driver.length && (this.dataSource.jdbcDriverClass = obj.driver[0]);
      }
    },
    handleEdit(row, e) {
      e.stopPropagation();
      this.drawerType = "edit";
      this.$set(this, "dataSource", {
        id: row.id,
        dataSourceType: row.dataSourceType,
        dataSourceName: row.dataSourceName,
        dataSourceGroup: row.dataSourceGroup,
        jdbcUsername: row.jdbcUsername,
        jdbcPassword: row.jdbcPassword,
        jdbcUrl: row.jdbcUrl,
        jdbcDriverClass: row.jdbcDriverClass,
        comments: row.comments,
      });
      this.drawerVisible = true;
    },
    handleDelete(row, e) {
      e.stopPropagation();
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.searchPageData();
            });
        },
      });
    },
    // 保存的行和选中行如果一致，就返回该样式
    setRowClassName(record, index) {
      return index === this.rowIndex ? "clickRowStyle" : "";
    },
    handleConnect() {
      this.$refs.dataSource.validate((valid) => {
        if (valid) {
          const req = {
            id: this.dataSource.id,
            dataSourceType: this.dataSource.dataSourceType,
            jdbcUsername: this.dataSource.jdbcUsername,
            jdbcPassword: this.dataSource.jdbcPassword,
            jdbcUrl: this.dataSource.jdbcUrl,
            jdbcDriverClass: this.dataSource.jdbcDriverClass,
          };
          this.$axios
            .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/test`, req)
            .then((res) => {
              this.$message.success(this.$t("TEST_CONNECT_SUCCESS"));
            });
        }
      });
    },
    save() {
      this.$refs.dataSource.validate((valid) => {
        if (valid) {
          if (this.drawerType === "add") {
            this.$axios
              .post(
                `${ApiConstant.PREFIX_CORE}/api/sys/datasource`,
                this.dataSource
              )
              .then((res) => {
                this.drawerVisible = false;
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.searchPageData();
              });
          } else if (this.drawerType === "edit") {
            this.$axios
              .put(
                `${ApiConstant.PREFIX_CORE}/api/sys/datasource`,
                this.dataSource
              )
              .then((res) => {
                this.drawerVisible = false;
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.searchPageData();
              });
          }
        }
      });
    },
    close() {
      this.drawerVisible = false;
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.i-form .form-row {
  padding: 0 !important;
}
/deep/.drawer-footer {
  position: absolute;
  bottom: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

/deep/.row_col_show {
  .ant-col {
    height: calc(100vh - 134px);
    padding: 14px 20px 0;
    border-right: 10px solid #f0f2f5;
  }
  .table_title {
    height: 30px;
    margin-bottom: 10px;
    font-weight: 550;
    font-size: 18px;
    line-height: 30px;
  }
  .table_style {
    .el-table__row td {
      cursor: pointer;
    }
  }
  .title_two {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .middlle_tabel {
    .ant-table-row {
      cursor: pointer;
    }
  }
  .pagination_position {
    position: absolute;
    right: 10px;
    bottom: 10px;
  }
  .button_left {
    padding: 0 !important;
    font-size: 18px !important;
    border: none;
  }
  .center_search {
    display: inline-block;
    width: 50%;
  }
  .ul_data_show {
    height: calc(100vh - 190px);
    overflow: scroll;
    li {
      line-height: 38px;
      height: 38px;
      cursor: pointer !important;
      .text_ellipsis {
        width: 56%;
        overflow: hidden;
        white-space: nowrap; /* 不换行 */
        text-overflow: ellipsis; /* 超出部分文字以...显示 */
      }
    }
    .a-button {
      color: #000;
    }
    .botton_show_key {
      display: block;
      width: 45%;
      text-align: right;
      .a-button {
        padding: 0 !important;
      }
    }
  }
  li:hover {
    color: #3dc2e5;
  }
  .rowBlue {
    color: #3dc2e5;
    background-color: #dfeff7;
  }
  .center_table .current-row > td {
    background: #a1eafd !important;
  }
  .center_table .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #a1eafd !important;
  }
}
/deep/.row_col_show:last-child {
  border-right: 0;
}
.height_100 {
  height: calc(100%);
}
.rulesStr {
  /deep/.s-table-tool {
    display: none;
  }
}
/deep/.ant-table-body,
.mega-design-table {
  max-height: calc(100vh - 230px);
  overflow-y: auto;
}
/deep/.clickRowStyle {
  background: #dfeff7;
}
</style>
