<template>
  <div class="sshManagement">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :data-source="tableData"
      :action-buttons="tableAction"
      :page.sync="page"
      :total="total"
      @search="searchPageData"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('SSH_MANAGEMENT:ADD')"
          type="primary"
          @click="handleAdd"
        >
          <a-icon type="plus" />
          {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('SSH_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
    </MomTable>
    <!-- 编辑抽屉 -->
    <MegaDrawer
      width="520"
      :title="$t('SERVER_CONFIG')"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-form-model slot="main" ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item :label="$t('SERVER_NAME')" prop="serverName">
          <a-input v-model="form.serverName" :placeholder="$t('PLACEENTER')" />
        </a-form-model-item>
        <a-form-model-item :label="$t('SSH_IP')" prop="sshIp">
          <a-input v-model="form.sshIp" :placeholder="$t('PLACEENTER')" />
        </a-form-model-item>
        <a-form-model-item :label="`SSH${$t('PORT')}`" prop="sshPort">
          <a-input v-model="form.sshPort" :placeholder="$t('PLACEENTER')" />
        </a-form-model-item>
        <a-form-model-item :label="`SSH${$t('ACCOUNT')}`" prop="sshUserName">
          <a-input v-model="form.sshUserName" :placeholder="$t('PLACEENTER')" />
        </a-form-model-item>
        <a-form-model-item :label="`SSH${$t('PASSWORD')}`" prop="sshPassword">
          <a-input
            v-model="form.sshPassword"
            type="password"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>
<script>
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaDrawer,
  },
  data() {
    return {
      page: 1,
      total: 0,
      drawerVisible: false,
      tableData: [],
      queryForm: {
        sshIp: "",
      },
      form: {
        id: "",
        serverName: "",
        sshIp: "",
        sshUserName: "",
        sshPassword: "",
        sshPort: "",
      }, // 表单
      // 表格的配置项
      tableColumns: [
        {
          dataIndex: "serverName",
          title: () => this.$t("SERVER_NAME"),
          minWidth: 200,
          sorter: false,
        },
        {
          dataIndex: "sshIp",
          title: () => this.$t("SSH_IP"),
          options: [],
          minWidth: 200,
        },
        {
          dataIndex: "sshPort",
          title: () => `SSH${this.$t("PORT")}`,
          minWidth: 200,
        },
        {
          dataIndex: "sshUserName",
          title: () => `SSH${this.$t("ACCOUNT")}`,
          minWidth: 200,
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          minWidth: 200,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          minWidth: 168,
        },
      ],
      tableAction: [
        (h, { record }) => (
          <span onClick={() => this.handleCmd(record)}>
            <a-icon
              type="desktop"
              style="color: #17698f"
              title={this.$t("SSH_REMOTE")}
            />
          </span>
        ),
        this.hasAuth("SSH_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("SSH_MANAGEMENT:DELETE") && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    // 查询表格配置项
    queryFormItem() {
      return this.$observable("queryFormItem", {
        sshIp: {
          label: () => this.$t("SSH_IP"),
          labelWidth: "90",
        },
      });
    },
    rules() {
      return {
        serverName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        sshIp: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        sshUserName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        sshPassword: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        sshPort: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  methods: {
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/monitor/ssh/search`, {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    handleAdd() {
      this.form = {
        id: "",
        serverName: "",
        sshIp: "",
        sshUserName: "",
        sshPassword: "",
        sshPort: "",
      }; // 表单
      this.drawerVisible = true;
    },
    handleEdit(row) {
      this.drawerVisible = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/monitor/ssh/get-by-id/${row.id}`)
        .then((res) => {
          this.form = res.data.data;
        });
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("DELETE"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/monitor/ssh/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({ id }) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/monitor/ssh/${id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleCmd(row) {
      window.open(`/upms/system/monitor/sshManagement/cmd?id=${row.id}`);
    },
    handleCancel() {
      this.drawerVisible = false;
      this.$refs.ruleForm.clearValidate();
    },
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/monitor/ssh`, this.form)
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.drawerVisible = false;
                this.$refs.MomTable?.query();
              });
          } else {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/monitor/ssh`, this.form)
              .then(() => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.drawerVisible = false;
                this.$refs.MomTable?.query();
              });
          }
        }
      });
    },
  },
};
</script>
