<!--数据源-->
<template>
  <div class="data-source-page">
    <div>
      <MomTable
        ref="MomTable"
        :row-selection="rowSelection"
        :columns="tableColumns"
        :data-source="tableData"
        :query-param="queryForm"
        :query-param-item="queryFormItem"
        row-key="id"
        :page.sync="page"
        :total="total"
        :action-buttons="tableAction"
        @search="searchPageData"
        @edit="handleEdit"
        @delete="handleDelete"
      >
        <div slot="toolbar" class="button-top-table">
          <a-button
            v-if="hasAuth('DATASOURCE_MANAGEMENT:ADD')"
            @click="handleAdd"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('DATASOURCE_MANAGEMENT:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </div>
      </MomTable>
    </div>
    <MegaDrawer
      :visible="drawerVisible"
      :title="drawerTitle"
      width="520"
      @close="drawerVisible = false"
    >
      <div slot="main">
        <a-form-model
          ref="dataSource"
          layout="vertical"
          :model="dataSource"
          :rules="rules"
        >
          <a-form-model-item
            :label="$t('DATA_SOURCE_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"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <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="$t('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 }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="$t('REMARK')" prop="remark">
            <a-input
              v-model="dataSource.remark"
              type="textarea"
              :placeholder="$t('PLACEENTER')"
              :rows="2"
              allow-clear
            />
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button 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="drawerVisible = false">
          <Icon type="icon-dir-f-rollback" :size="18" />
          {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaDrawer>
  </div>
</template>

<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "Index",
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      queryForm: {
        dataSourceName: "",
        dataSourceType: null,
      },
      tableAction: [
        this.hasAuth("DATASOURCE_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("DATASOURCE_MANAGEMENT:DELETE") && "delete",
      ],
      sortParams: null,
      // 表格列
      tableColumns: [
        {
          dataIndex: "dataSourceType",
          title: () => this.$t("DATA_SOURCE_TYPE"),
          width: 200,
          sorter: false,
        },
        {
          dataIndex: "dataSourceName",
          title: () => this.$t("DATA_SOURCE_NAME"),
          width: 340,
          sorter: false,
        },
        // {
        //   dataIndex: "dataSourceGroup",
        //   title: () => this.$t("DATA_SOURCE_GROUP"),
        //   width: 300,
        //   sorter: false,
        // },
        {
          ellipsis: true,
          dataIndex: "jdbcUrl",
          sorter: false,
          title: () => this.$t("JDBC_URL"),
          minWidth: 400,
        },
        {
          dataIndex: "remark",
          sorter: false,
          title: () => this.$t("REMARK"),
          width: 300,
        },
      ],
      tableData: [],
      page: 1,
      total: 0,
      drawerVisible: false,
      drawerType: "add",
      passwordInput: false,
      dataSourceTypeOptions: [],
      dataSource: {
        id: null,
        dataSourceType: "",
        dataSourceName: "",
        // dataSourceGroup: "Default",
        jdbcUserName: "",
        jdbcPassword: "",
        jdbcDriverClass: "",
        jdbcUrl: "",
        remark: "",
      },
      jdbcDriverClassOptions: [],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    // 表格查询条件
    queryFormItem() {
      return this.$observable("queryFormItem", {
        dataSourceName: {
          label: () => this.$t("DATA_SOURCE_NAME"),
        },
        dataSourceType: {
          label: () => this.$t("DATA_SOURCE_TYPE"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "desc",
            value: "desc",
          },
        },
      });
    },
    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 "";
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/types`, {})
        .then((res) => {
          this.dataSourceTypeOptions = res.data.data;
          this.queryFormItem.dataSourceType.options = res.data.data;
        });
    },
    // 添加
    handleAdd() {
      this.drawerType = "add";
      this.$set(this, "dataSource", {
        id: null,
        dataSourceType: "",
        dataSourceName: "",
        // dataSourceGroup: "Default",
        jdbcUserName: "",
        jdbcPassword: "",
        jdbcDriverClass: "",
        jdbcUrl: "",
        remark: "",
      });
      this.drawerVisible = true;
    },
    // 获取数据列表
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/search`, {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data?.records;
          this.total = res.data.data?.total;
        });
    },
    // 展示密码 之后的修改按钮
    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
        obj.driver.length && (this.dataSource.jdbcDriverClass = obj.driver[0]);
      }
    },
    // 编辑
    handleEdit(row) {
      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,
        remark: row.remark,
      });
      this.drawerVisible = true;
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        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/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 删除
    handleDelete(row) {
      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.$refs.MomTable?.query();
            });
        },
      });
    },
    // 测试连接
    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`, {
              params: 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.$refs.MomTable?.query();
              });
          } 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.$refs.MomTable?.query();
              });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-drawer {
  width: 25% !important;
  min-width: 480px;
  max-width: 700px;
}
/deep/ .el-drawer__header {
  padding: 15px 16px 15px 30px;
}
/deep/ .i-form .form-row {
  padding: 0 !important;
}
/deep/ .drawer-footer {
  position: absolute;
  bottom: 80px;
  z-index: 5;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  background: #fff;
}
</style>
