<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :query-param="search"
      :query-param-item="queryItemConfig"
      :columns="tableColumns"
      :data-source="tableData"
      :action-buttons="actionButtons"
      :page.sync="page"
      :total="total"
      :show-enable-flag="true"
      @edit="handleEdit"
      @delete="handleDelete"
      @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'
          )
      "
    >
      <div slot="toolbar">
        <!-- 新增 -->
        <a-button
          v-if="hasAuth('BI_CONFIG:ADD')"
          icon="plus"
          @click="handleOpenDrawer('add')"
        >
          {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('BI_CONFIG:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(enableFlagList, text) }}
        </span>
      </div>
    </MomTable>
    <MegaDrawer
      width="700"
      :visible="drawer"
      :title="drawerType !== 'edit' ? $t('ADD') : $t('EDIT')"
      @close="drawer = false"
      @cancel="drawer = false"
      @ok="handleSave"
    >
      <MegaForm
        slot="main"
        :query-param="formData"
        :query-param-item="formItemConfig"
        :query-param-rules="rules"
      ></MegaForm>
    </MegaDrawer>
  </div>
</template>

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

export default {
  name: "LabSett",
  components: {
    MegaForm,
    MegaDrawer,
  },
  data() {
    return {
      enableFlagList: [],
      // 查询表单数据
      search: {
        name: null,
        type: null,
      },
      paramNames: [],
      selectData: {
        formLabelVersions: [], // 根据标签号筛选出标签版本
      },
      tableData: [],
      total: 0,
      page: 1,
      drawer: false,
      drawerType: "add",
      formData: {
        code: "",
        name: "",
        type: undefined,
        linkServerAddress: "",
        authServerAddress: "",
        authParamList: [],
      },
      tempAuthParamList: [],
      actionButtons: [
        this.hasAuth(`BI_CONFIG:EDIT`) && "edit",
        this.hasAuth(`BI_CONFIG:DELETE`) && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    rules() {
      return {
        code: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message:
              this.$t("COLUMN:COMMON:PLACEENTER") +
              32 +
              this.$t("TIPS:COMMON:LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message:
              this.$t("COLUMN:COMMON:PLACEENTER") +
              32 +
              this.$t("TIPS:COMMON:LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        linkServerAddress: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        authServerAddress: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    queryItemConfig() {
      return this.$observable("queryItemConfig", {
        // 服务商编码
        code: {
          label: () => this.$t("BI_SERVER_CODE"),
        },
        // 服务商名称
        name: {
          label: () => this.$t("SERVER_NAME"),
        },
        // 服务商类型
        type: {
          label: () => this.$t("TYPE"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        linkServerAddress: {
          label: () => this.$t("EXTERNAL_LINK_SERVER_ADDRESS"),
        },
        authServerAddress: {
          label: () => this.$t("AUTHORIZATION_SERVER_ADDRESS"),
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "code",
          width: 152,
          title: () => this.$t("BI_SERVER_CODE"),
        },
        {
          dataIndex: "name",
          title: () => this.$t("SERVER_NAME"),
          width: 260,
        },
        {
          dataIndex: "type",
          title: () => this.$t("TYPE"),
          width: 100,
        },
        // 外链服务器地址
        {
          dataIndex: "linkServerAddress",
          title: () => this.$t("EXTERNAL_LINK_SERVER_ADDRESS"),
          ellipsis: true,
          width: 260,
        },
        // 授权服务器地址
        {
          dataIndex: "authServerAddress",
          title: () => this.$t("AUTHORIZATION_SERVER_ADDRESS"),
          ellipsis: true,
          width: 260,
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          width: 80,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 162,
        },
      ];
    },
    formItemConfig() {
      return this.$observable("formItemConfig", {
        // 服务商编码
        code: {
          label: () => this.$t("BI_SERVER_CODE"),
        },
        name: {
          label: () => this.$t("SERVER_NAME"),
          itemType: "input",
        },
        type: {
          label: () => this.$t("TYPE"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          on: {
            change: (val) => {
              this.typeChange(val);
            },
          },
        },
        linkServerAddress: {
          label: () => this.$t("EXTERNAL_LINK_SERVER_ADDRESS"),
          itemType: "input",
        },
        authServerAddress: {
          label: () => this.$t("AUTHORIZATION_SERVER_ADDRESS"),
          itemType: "input",
        },
        authParamList: {
          label: () => this.$t("AUTHORIZATION_PARAMS"),
          itemType: "custom",
          customRender: () => {
            return (
              <div>
                {this.formData.authParamList.map((item, index) => {
                  const formModelProps = {
                    props: {
                      model: { ...item },
                    },
                  };
                  return (
                    <a-form-model key={index} {...formModelProps}>
                      <a-row gutter={10} type="flex">
                        <a-col span={9}>
                          <a-form-model-item label="">
                            <a-input
                              v-model={item.key}
                              placeholder={this.$t(
                                "PLEASE_ENTER_PARAMETER_NAME"
                              )}
                            />
                          </a-form-model-item>
                        </a-col>
                        <a-col span={10}>
                          <a-form-model-item label="">
                            <a-input
                              v-model={item.value}
                              placeholder={this.$t(
                                "PLEASE_ENTER_PARAMETER_VALUE"
                              )}
                            />
                          </a-form-model-item>
                        </a-col>
                        <a-col span={5}>
                          <a-form-model-item label="">
                            <a-button
                              v-show={this.formData.authParamList.length > 1}
                              type="link"
                              icon="delete"
                              class="text-error"
                              onClick={() =>
                                this.deleteSubForm(index)
                              }></a-button>
                            <a-button
                              v-show={
                                index === this.formData.authParamList.length - 1
                              }
                              type="link"
                              icon="plus"
                              onClick={() => this.addSubForm(index)}></a-button>
                          </a-form-model-item>
                        </a-col>
                      </a-row>
                    </a-form-model>
                  );
                })}
              </div>
            );
          },
        },
      });
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    typeChange(value) {
      if (value === "TABLEAU") {
        if (this.tempAuthParamList.length > 0) {
          if (this.drawerType === "add") {
            this.formData.authParamList = [
              { key: "username", value: "" },
              { key: "target_site", value: "" },
            ];
          } else {
            this.formData.authParamList = this.tempAuthParamList;
          }
        } else {
          this.formData.authParamList = [
            { key: "username", value: "" },
            { key: "target_site", value: "" },
          ];
        }
      } else {
        this.formData.authParamList = [
          {
            key: "",
            value: "",
          },
        ];
      }
    },
    // 初始化选项
    init() {
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.enableFlagList = res.data.data;
      });
      // 获取标签类型
      this.getDictByCode("DIC:CORE:REPORT_SEVER_TYPE").then((res) => {
        this.queryItemConfig.type.options = res.data.data;
        this.formItemConfig.type.options = res.data.data;
      });
    },
    // 分页查询
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/report/report-server/search`, {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 编辑
    handleEdit(row) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/report/report-server/get-by-id/${row.id}`
        )
        .then((res) => {
          this.handleOpenDrawer("edit", res.data.data);
        });
    },
    // 新增或者编辑
    handleOpenDrawer(type, row) {
      this.drawerType = type;
      this.drawer = true;
      if (type === "edit") {
        const tempObj = JSON.parse(JSON.stringify(row));
        [
          "id",
          "code",
          "name",
          "type",
          "linkServerAddress",
          "authServerAddress",
        ].forEach((key) => {
          this.$set(this.formData, key, row[key]);
        });
        if (tempObj.authParamList) {
          this.formData.authParamList = tempObj.authParamList;
          this.tempAuthParamList = tempObj.authParamList;
        }
        if (
          !this.formData.authParamList ||
          this.formData.authParamList.length === 0
        ) {
          this.formData.authParamList = [
            {
              key: "",
              value: "",
            },
          ];
        }
        this.$set(this, "formData", this.formData);
      } else if (type === "add") {
        this.$set(this.formData, "authParamList", [
          {
            key: "",
            value: "",
          },
        ]);
        [
          "code",
          "name",
          "type",
          "linkServerAddress",
          "authServerAddress",
        ].forEach((key) => {
          this.$set(this.formData, key, undefined);
        });
      }
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: true,
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/report/report-server/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    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"),
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/report/report-server/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"),
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/report/report-server/${row.id}`
            )
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleSave() {
      // 将未选择条件的子数据删除
      const data = { ...this.formData };
      data.authParamList = data.authParamList.filter((item) => item.key);
      // 组请求

      if (this.drawerType === "edit") {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/report/report-server`, data)
          .then((res) => {
            this.$message.success(this.$t("UPDATE_SUCCESS"));
            this.$refs.MomTable?.query();
            this.drawer = false;
          });
      } else {
        this.$axios
          .post(`${ApiConstant.PREFIX_CORE}/api/report/report-server`, data)
          .then((res) => {
            this.$message.success(this.$t("ADD_SUCCESS"));
            this.$refs.MomTable?.query();
            this.drawer = false;
          });
      }
    },
    // 对话框取消
    handleCancel() {
      this.drawer = false;
    },
    // 增加条件
    addSubForm(index) {
      this.formData.authParamList.push({
        key: "",
        value: "",
      });
    },
    // 删除条件
    deleteSubForm(index) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        onOk: () => {
          if (this.formData.authParamList.length > 1) {
            this.formData.authParamList.splice(index, 1);
          }
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/ .el-drawer {
  width: 40% !important;
  min-width: 580px;
  max-width: 700px;
  .el-input,
  .el-select,
  .el-date-editor,
  .el-input-number,
  .el-textarea {
    max-width: 460px !important;
  }
  .el-row {
    margin: 0;
  }
  .btns {
    position: relative;
    display: inline-block;
    min-width: 71px;
    text-align: right;
    [class^="el-icon-"] {
      position: absolute;
      color: #1890ff;
      font-size: 18px !important;
      cursor: pointer;
    }
    .el-icon-delete {
      top: 10px;
      right: 35px;
    }
    .el-icon-plus {
      top: 10px;
      right: 0;
    }
  }
}
/deep/ .el-drawer__header {
  margin-bottom: 15px;
  padding: 15px 16px 15px 30px;
}
/deep/ .i-form .form-row {
  padding: 0 !important;
}
/deep/ .drawer-footer {
  position: absolute;
  right: 20px;
  bottom: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
.button-top-table {
  margin-bottom: 12px;
}
</style>
