<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryParam"
      :query-param-item="queryFormItem"
      :action-buttons="actionButtons"
      :total="total"
      :page.sync="page"
      :show-enable-flag="true"
      :mega-extend="{
        rowAction: {
          width: 150,
        },
      }"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
      @edit="handleEdit"
      @copy="handleCopy"
      @delete="handleDelete"
      @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'
          )
      "
    >
      <a-row slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('ROLE_MANAGEMENT:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('ROLE_MANAGEMENT:EXPORT')"
          class="btn__green-1"
          icon="to-top"
          :disabled="!tableData.length"
          @click="handleExportExcel"
        >
          {{ $t("EXPORT") }}
        </a-button>
        <a-button
          v-if="hasAuth('ROLE_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </a-row>

      <span slot="roleCategory" slot-scope="text">
        {{ getAttrValue(queryFormItem.roleCategory.options, text) }}
      </span>
      <div slot="enableFlag" slot-scope="text, record">
        <span
          :style="
            record.enableFlag == 'Y' ? 'color: #0fd19c' : 'color: #d45f5f'
          "
          >{{ getAttrValue(stateList, record.enableFlag) }}</span
        >
      </div>
    </MomTable>
  </div>
</template>

<script>
import ApiConstant from "@/api/ApiConstant";
import { exportExcel } from "@/utils";

export default {
  data() {
    return {
      // 表格的配置项
      tableColumns: [
        {
          dataIndex: "roleCode",
          minWidth: 300,
          title: () => this.$t("ROLE_CODE"), // 角色编码
        },
        {
          dataIndex: "roleName",
          minWidth: 320,
          title: () => this.$t("ROLE_NAME"), // 角色名称
        },
        {
          dataIndex: "roleCategory",
          width: 220,
          sorter: false,
          title: () => this.$t("ROLE_CATEGORY"), // 角色类型
          scopedSlots: { customRender: "roleCategory" },
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          width: 80,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime", // 更新时间
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ],
      tableData: [],
      stateList: [],
      selectedRowKeys: [],
      sortParams: null,
      page: 1, // 页码
      total: 0, // 每页个数
      title: "", // 弹框的标题
      dialogVisble: false, // 弹框的显示 隐藏
      // 查询的表单的配置项
      queryParam: {
        roleCode: "",
        roleName: "",
        roleCategory: "",
      },
      actionButtons: [
        this.hasAuth("ROLE_MANAGEMENT:COPY") && "copy",
        this.hasAuth("ROLE_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("ROLE_MANAGEMENT:DELETE") && "delete",
        (h, { record }) =>
          this.hasAuth("ROLE_MANAGEMENT:ASSGIN_USER") && (
            <span
              class="text-primary cursor-pointer"
              title={this.$t("ASSGIN_USER")}
              onClick={() => this.handleAuthorizeUser(record)}
            >
              <a-icon type="man" />
            </span>
          ),
      ],
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        roleCode: {
          itemType: "input",
          label: () => this.$t("ROLE_CODE"), // 角色编码
        },
        roleName: {
          itemType: "input",
          label: () => this.$t("ROLE_NAME"), // 角色名称
        },
        roleCategory: {
          itemType: "select",
          label: () => this.$t("ROLE_CATEGORY"), // 角色类型
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
  },
  methods: {
    beforeSearch() {
      this.getDictByCode("DIC:CORE:SYS_ROLE_TYPE").then((res) => {
        this.queryFormItem.roleCategory.options = res.data.data;
      });
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.stateList = res?.data?.data || [];
      });
    },
    // 启用、禁用
    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/sys/role/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 后台分页查询
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/role/search`, {
          params: {
            ...params,
            appId: "0",
          },
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 导出
    handleExportExcel() {
      const params = {
        page: this.page,
        appId: "0",
        size: this.$store.state.pagination.pageSize,
        ...this.queryParam,
      };
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/role/export`,
        method: "get",
        params,
        responseType: "blob",
      }).then((res) => {
        exportExcel(res.data, `${this.$t("ROLE_MANAGEMENT")}.xls`);
      });
    },
    // 点击新增
    handleAdd() {
      this.$router.push({
        path: "/upms/system/setting/role/add",
      });
    },
    handleCopy(row) {
      this.$router.push({
        path: "/upms/system/setting/role/add",
        query: {
          id: row.id,
        },
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$router.push({
        path: "/upms/system/setting/role/edit",
        query: {
          id: row.id,
        },
      });
    },
    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/role/batch-delete`, {
                params: {
                  ids: this.selectedRowKeys.join(","),
                },
              })
              .then((res) => {
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                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("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/sys/role/${id}`)
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 点击表格行内的分配用户
    handleAuthorizeUser(row) {
      this.$router.push({
        path: "/upms/system/setting/role/authorizeUser",
        query: {
          roleId: row.id,
          roleName: row.roleName,
        },
      });
    },
  },
};
</script>
<style lang="less">
.icon-defult {
  font-weight: 600;
}
</style>
