<template>
  <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="actionButtons"
      :show-enable-flag="true"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <template slot="toolbar">
        <a-button
          v-if="hasAuth('SYNCHRONIZATION_SETTINGS:ADD')"
          @click="handleAdd"
        >
          <a-icon type="plus" />
          {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('SYNCHRONIZATION_SETTINGS:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </template>
      <div slot="enableFlag" slot-scope="text, record">
        <span
          :style="
            record.enableFlag == 'Y' ? 'color: #0fd19c' : 'color: #d45f5f'
          "
        >
          {{ formatData(stateList, record.enableFlag) }}
        </span>
      </div>
    </MomTable>
    <MegaDrawer
      :title="drawerType === 'add' ? $t('ADD') : $t('EDIT')"
      :visible.sync="drawerVisible"
      width="520"
      @close="cancel"
    >
      <template slot="main">
        <a-form-model
          ref="drawerForm"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <a-form-model-item :label="$t('CODE')" prop="dataPushConfigCode">
            <a-input
              v-model="form.dataPushConfigCode"
              :placeholder="$t('PLACEENTER')"
              :disabled="drawerType !== 'add'"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('SYSTEM_NAME')" prop="systemCode">
            <a-select
              v-model="form.systemCode"
              class="d-inline-block"
              :placeholder="$t('PLACESELECT')"
            >
              <a-select-option
                v-for="(item, index) in menuAllList"
                :key="index"
                :value="item.value"
              >
                {{ $t(item.label) }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="$t('SWITCH_NAME')" prop="mqExchangeName">
            <a-input
              v-model="form.mqExchangeName"
              type="text"
              :row="2"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('QUEUE_NAME')" prop="mqQueueName">
            <a-input
              v-model="form.mqQueueName"
              type="text"
              :row="2"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('DATA_TYPE')" prop="dataTypeList">
            <a-checkbox-group v-model="form.dataTypeList">
              <a-checkbox
                v-for="item in checkoutList"
                :key="item.code"
                :value="item.code"
              >
                {{ $t(item.i18nCode) }}
              </a-checkbox>
            </a-checkbox-group>
          </a-form-model-item>
        </a-form-model>
      </template>
      <footer slot="footer">
        <a-button type="primary" @click="confirm">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="cancel">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
  </div>
</template>

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

export default {
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      // 查询的表单的配置项
      queryForm: {
        systemCode: "",
      },
      sort: {},
      sortParams: null,
      nameList: [],
      // tableColumns: [],
      tableData: [],
      page: 1, // 页码
      total: 0,
      drawerVisible: false, // 弹框的显示 隐藏
      drawerType: "add", // add or edit
      // 新增或修改的表单配置项
      form: {
        id: null,
        dataPushConfigCode: "", // 编码
        systemCode: "", // 系统编码
        mqExchangeName: "", //	交换机名称
        mqQueueName: "", // 队列名称
        dataTypeList: [], // 系统类型
      },
      checkoutList: [],
      isFixHeight: true,
      tableHeight: null,
      minusHeight: 0,
      menuAllList: [],
      quipmentList: [],
      loading: false,
      actionButtons: [
        (h, value, a, b) => (
          <span>
            {this.hasAuth("SYNCHRONIZATION_SETTINGS:EDIT") && (
              <Icon
                onClick={() => this.handleEdit(value.record)}
                type="icon-edit-edit"
                size={15}
                style="color:#01baea;cursor: pointer;"
                title={this.$t("EDIT")}
              />
            )}
          </span>
        ),
        (h, value, a, b) => (
          <span>
            {this.hasAuth("SYNCHRONIZATION_SETTINGS:DELETE") && (
              <Icon
                onClick={() => this.handleDelete(value.record)}
                type="icon-edit-delete"
                size={15}
                style="color:#d45f5f;cursor: pointer;"
                title={this.$t("DELETE")}
              />
            )}
          </span>
        ),
      ],
      defaultList: [
        {
          dataIndex: "systemCode", // 系统名称
          title: () => this.$t("SYSTEM_NAME"),
          minWidth: 155,
        },
        {
          dataIndex: "mqExchangeName", // 交换机名称
          title: () => this.$t("SWITCH_NAME"),
          minWidth: 300,
        },
        {
          dataIndex: "mqQueueName", // 队列名称
          minWidth: 300,
          title: () => this.$t("QUEUE_NAME"),
        },
        {
          dataIndex: "enableFlag",
          align: "left",
          sorter: false,
          minWidth: 150,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
      ],
      resList: [],
      stateList: [],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    realHeight() {
      if (this.isFixHeight) {
        return this.tableHeight;
      }
      return this.paramsHeight;
    },
    rules() {
      return {
        systemCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        mqExchangeName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        mqQueueName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        dataTypeList: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
      };
    },
    queryFormItem() {
      return {
        systemCode: {
          label: () => this.$t("SYSTEM_NAME"), // 系统名称
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      };
    },
    tableColumns() {
      return [...this.defaultList, ...this.resList];
    },
  },
  methods: {
    beforeSearch() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/data-push-config/get-data-type-list`
        )
        .then((res) => {
          this.checkoutList = res.data.data;
        });
      this.getDictByCode("DIC:CORE:SUB_SYSTEM").then((res) => {
        this.menuAllList = res.data.data;
        this.queryFormItem.systemCode.options = res.data.data;
      });
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.stateList = res?.data?.data || [];
      });
    },
    // 点击新增
    handleAdd() {
      this.$set(this, "form", {
        id: null,
        dataPushConfigCode: "", // 编码
        systemCode: "", // 系统编码
        mqExchangeName: "", //	交换机名称
        mqQueueName: "", // 队列名称
        dataTypeList: [], // 系统类型
      });
      this.drawerType = "add";
      this.drawerVisible = true;
    },
    // 后台分页查询
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/data-push-config/search`, {
          params,
        })
        .then((res) => {
          const arr = res.data.data.records;
          this.tableData = [];
          const list = [];
          if (arr.length > 0) {
            this.nameList = Object.keys(arr[0]);
            if (res.data.data.total > 0) {
              arr.forEach((item, index) => {
                this.tableData[index] = {};
                this.nameList.forEach((element, i) => {
                  this.tableData[index][element] =
                    item[element] === null ? 0 : item[element];
                });
              });
            }
            this.nameList.forEach((item) => {
              const name = this.checkoutList.filter((value, index) => {
                return value.code === item ? value : "";
              });
              const obj = {
                dataIndex: item,
                title: () => this.$t(`${name[0]?.i18nCode}`),
                width: 120,
                customRender: (text) => {
                  return (
                    <div>
                      {+text === 1 ? (
                        <Icon
                          type="icon-ins-check"
                          size={22}
                          style="color: rgb(15, 209, 156);font-weight: bold;">
                          {" "}
                        </Icon>
                      ) : (
                        <Icon type="icon-ins-close" size={16} />
                      )}
                    </div>
                  );
                },
              };
              if (
                ![
                  "systemCode",
                  "id",
                  "mqExchangeName",
                  "mqQueueName",
                  "updateTime",
                  "updateBy",
                  "enableFlag",
                  "dataPushConfigCode",
                ].includes(item)
              ) {
                list.push(obj);
              }
              this.resList = list;
            });
            this.total = res.data.data.total;
          }
        });
    },
    cancel() {
      this.$refs.drawerForm.resetFields();
      this.$refs.drawerForm.clearValidate();
      this.drawerVisible = false;
    },
    confirm() {
      this.$refs.drawerForm.validate((valid) => {
        if (valid) {
          const req = {
            ...this.form,
          };
          if (this.drawerType === "add") {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/data-push-config`, req)
              .then((res) => {
                this.$message.success(
                  this.drawerType === "add"
                    ? this.$t("ADD_SUCCESS")
                    : this.$t("EDIT_SUCCESS")
                );
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          } else {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/data-push-config`, req)
              .then((res) => {
                this.$message.success(
                  this.drawerType === "add"
                    ? this.$t("ADD_SUCCESS")
                    : this.$t("EDIT_SUCCESS")
                );
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          }
        }
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/data-push-config/get-by-id/${row.id}`
        )
        .then((res) => {
          this.$set(this, "form", {
            id: res.data.data.id,
            dataPushConfigCode: res.data.data.dataPushConfigCode, // 系统编码
            systemCode: res.data.data.systemCode, // 系统编码
            mqExchangeName: res.data.data.mqExchangeName, //	交换机名称
            mqQueueName: res.data.data.mqQueueName, // 队列名称
            dataTypeList: res.data.data.dataTypeList, // 系统类型
          });
        });
      this.drawerType = "edit";
      this.drawerVisible = true;
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/data-push-config/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    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/data-push-config/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("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/data-push-config/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.ant-checkbox-wrapper {
  line-height: 36px;
}
/deep/.ant-checkbox-wrapper:first-child {
  margin-left: 8px;
}
</style>
