<!--执行器管理页面-->
<template>
  <div class="executor-page">
    <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"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
    >
      <template slot="addressType" slot-scope="text, record">
        <span>{{ formatData(tableColumns[2], record.addressType) }}</span>
      </template>
      <div slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('ACTUATOR_MANAGEMENT:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('ACTUATOR_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
    </MomTable>
    <MegaDrawer
      ref="drawerForm"
      :title="drawerTitle"
      :visible="drawerVisible"
      width="520"
      @ok="save"
      @cancel="close"
      @close="close"
    >
      <div slot="main">
        <a-form-model
          slot="iDialogForm"
          ref="newForm"
          layout="vertical"
          :model="form"
        >
          <a-form-model-item
            prop="appName"
            :label="$t('APPLICATION_NAME')"
            :rules="[
              {
                required: true,
                message: $t('PLACEENTER'),
                trigger: 'blur',
              },
            ]"
          >
            <a-input v-model="form.appName" :placeholder="$t('PLACEENTER')" />
          </a-form-model-item>
          <a-form-model-item
            prop="title"
            :label="$t('NAME')"
            :rules="{
              required: true,
              message: $t('PLACEENTER'),
              trigger: 'blur',
            }"
          >
            <a-input v-model="form.title" :placeholder="$t('PLACEENTER')" />
          </a-form-model-item>
          <a-form-model-item
            prop="addressType"
            :label="$t('REGISTER_WAY')"
            :rules="{
              required: true,
              message: $t('PLACESELECT'),
              trigger: 'change',
            }"
          >
            <a-radio-group v-model="form.addressType">
              <a-radio
                v-for="(item, index) in addressTypeOptions"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item
            prop="addressList"
            :label="$t('MACHINE_ADDRESS')"
            :rules="{
              required: !isAuto,
              message: $t('PLACEENTER'),
              trigger: 'blur',
            }"
          >
            <a-input
              v-model="form.addressList"
              :placeholder="$t('PLACEENTER')"
              :disabled="drawerType === 'edit' && isAuto"
              allow-clear
            />
          </a-form-model-item>
        </a-form-model>
      </div>
    </MegaDrawer>
  </div>
</template>

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

export default {
  name: "IndexVue",
  components: {
    MegaDrawer,
  },
  data() {
    return {
      queryForm: {
        appName: "",
        title: "",
        addressType: "",
      },
      // 表格列配置项
      tableColumns: [
        {
          dataIndex: "appName",
          title: () => this.$t("APPLICATION_NAME"),
          minWidth: 300,
          sorter: false,
        },
        {
          dataIndex: "title",
          title: () => this.$t("NAME"),
          minWidth: 300,
          sorter: false,
        },
        {
          key: "addressType",
          title: () => this.$t("REGISTER_WAY"),
          scopedSlots: { customRender: "addressType" },
          options: [],
          sorter: false,
          minWidth: 240,
        },
        {
          dataIndex: "addressList",
          title: () => this.$t("MACHINE_ADDRESS"),
          minWidth: 300,
          sorter: false,
        },
      ],
      tableData: [],
      page: 1,
      total: 0,
      drawerVisible: false,
      drawerType: "add", // 新增(add) 或 编辑(edit)
      form: {
        id: null,
        appName: "",
        title: "",
        groupOrder: null,
        addressType: "1",
        addressList: "",
      },
      addressTypeOptions: [],
      tableAction: [
        this.hasAuth("ACTUATOR_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("ACTUATOR_MANAGEMENT:DELETE") && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    // 列表查询条件
    queryFormItem() {
      return this.$observable("queryFormItem", {
        appName: {
          label: () => this.$t("APPLICATION_NAME"),
        },
        title: {
          label: () => this.$t("NAME"),
        },
        addressType: {
          label: () => this.$t("REGISTER_WAY"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    drawerTitle() {
      if (this.drawerType === "add") {
        return this.$t("ADD");
      }
      if (this.drawerType === "edit") {
        return this.$t("EDIT");
      }
      return "";
    },
    isAuto() {
      return this.form.addressType === "0";
    },
  },
  async created() {
    await this.queryDictData();
  },
  methods: {
    // 获取词典
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:CORE:JOB_EXECUTOR_ADDRESS_TYPE`), // 注册方式
      ]).then(([typeRes]) => {
        this.addressTypeOptions = typeRes.data.data;
        this.queryFormItem.addressType.options = typeRes.data.data;
        this.tableColumns[2].options = typeRes.data.data;
      });
    },
    // 编辑
    handleEdit(row) {
      this.drawerType = "edit";
      this.$set(this, "form", {
        id: row.id,
        appName: row.appName,
        title: row.title,
        groupOrder: row.groupOrder || 1,
        addressType: row.addressType,
        addressList: row.addressList,
      });
      this.drawerVisible = true;
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        if (this.tableData.length === 1) {
          this.$message.error(this.$t("REJECT_DELETION"));
        } else if (this.tableData.length === this.selectedRowKeys.length) {
          this.$message.error(this.$t("REJECT_DELETION"));
        } else {
          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(`/job-server/api/job-group/batch-delete`, {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                })
                .then((res) => {
                  this.selectedRowKeys = [];
                  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(`/job-server/api/job-group/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 新增
    handleAdd() {
      this.drawerType = "add";
      this.drawerVisible = true;
      this.$set(this, "form", {
        id: null,
        appName: "",
        title: "",
        groupOrder: null || 1,
        addressType: "1",
        addressList: "",
      });
    },
    // 获取列表数据
    searchPageData(req) {
      this.$axios
        .get(`/job-server/api/job-group/search`, { params: req })
        .then((res) => {
          this.tableData = res.data.data.records.map((item) => ({
            ...item,
            addressType: `${item.addressType}`,
          }));
          this.total = res.data.data.total;
        });
    },
    formatData(data, status) {
      const result = data.options.find(
        (item) => item.value === status.toString()
      );
      return result ? result.label : "";
    },
    // 保存
    save() {
      this.$refs.newForm.validate((valid) => {
        if (valid) {
          if (this.drawerType === "add") {
            this.$axios
              .post(`/job-server/api/job-group`, this.form)
              .then((res) => {
                this.drawerVisible = false;
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
              });
          } else if (this.drawerType === "edit") {
            this.$axios
              .put(`/job-server/api/job-group`, this.form)
              .then((res) => {
                this.drawerVisible = false;
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
              });
          }
        }
      });
    },
    close() {
      this.drawerVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.drawer-footer {
  position: absolute;
  bottom: 80px !important;
  z-index: 5;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  background: #fff;
}
/deep/.ant-table td {
  white-space: nowrap;
}
</style>
