<template>
  <div class="box-main">
    <div>
      <MomTable
        ref="MomTable"
        :row-selection="rowSelection"
        :query-param="queryForm"
        :query-param-item="queryFormItem"
        row-key="id"
        :page.sync="page"
        :total="total"
        :columns="tableColumns"
        :data-source="tableData"
        :action-buttons="tableAction"
        @edit="handleEdit"
        @delete="handleDelete"
        @search="searchPageData"
      >
        <div slot="toolbar" class="button-top-table">
          <a-button v-if="hasAuth('CLIENT_MANAGEMENT:ADD')" @click="handleAdd">
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('CLIENT_MANAGEMENT:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </div>
        <template slot="autoapprove" slot-scope="text, record">
          <span>{{ formatData(yesNoList, record.autoapprove) }}</span>
        </template>
      </MomTable>
    </div>
    <MegaDrawer
      width="520"
      :title="title"
      :visible="drawerVisible"
      @close="handleCancel"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-form-model
        slot="main"
        ref="ruleForm"
        layout="vertical"
        :rules="rules"
        :model="form"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item :label="$t('CLIENT_ID')" prop="clientId">
              <a-input
                v-model="form.clientId"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('CLIENT_SECRET')" prop="clientSecret">
              <a-input
                v-model="form.clientSecret"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('SCOPE')" prop="scope">
              <a-input v-model="form.scope" :placeholder="$t('PLACEENTER')" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('AUTH_TYPE')"
              prop="authorizedGrantTypes"
            >
              <a-select v-model="form.authorizedGrantTypes" mode="multiple">
                <a-select-option
                  v-for="(item, index) in authTypeList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('TOKEN_VALIDITY')"
              prop="accessTokenValidity"
            >
              <a-input
                v-model="form.accessTokenValidity"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('REFRESH_TOKEN_VALIDITY')"
              prop="refreshTokenValidity"
            >
              <a-input
                v-model="form.refreshTokenValidity"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('AUTO_APPROVE')" prop="autoapprove">
              <a-select v-model="form.autoapprove">
                <a-select-option
                  v-for="(item, index) in yesNoList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('AUTH_MODEL')" prop="authorities">
              <a-input
                v-model="form.authorities"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('RESOURCE_ID')" prop="resourceIds">
              <a-input
                v-model="form.resourceIds"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('REDIRECTION_ADDRESS')"
              prop="webServerRedirectUri"
            >
              <a-input
                v-model="form.webServerRedirectUri"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('ADDITIONAL_INFO')"
              prop="additionalInformation"
            >
              <a-textarea
                v-model="form.additionalInformation"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </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 {
      drawerVisible: false,
      // 查询sort
      sortParams: null,
      tableData: [], // 表格数据
      // 查询的表单的配置项
      queryForm: {
        clientId: "",
      },
      tableAction: [
        this.hasAuth("CLIENT_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("CLIENT_MANAGEMENT:DELETE") && "delete",
      ],
      title: "", // 弹框的标题
      // 新增或修改的表单配置项
      form: {
        id: "",
        clientId: "",
        clientSecret: "",
        scope: "all",
        authorizedGrantTypes: [],
        refreshTokenValidity: "",
        accessTokenValidity: "",
        autoapprove: "",
        authorities: "",
        resourceIds: "",
        webServerRedirectUri: "",
        additionalInformation: "",
      },
      total: 0,
      page: 1,
      authTypeList: [
        { label: "authorization_code", value: "authorization_code" },
        { label: "password", value: "password" },
        { label: "refresh_token", value: "refresh_token" },
        { label: "implicit", value: "implicit" },
        { label: "client_credentials", value: "client_credentials" },
      ], // 授权类型
      yesNoList: [], // 是否
      companyList: [], // 公司列表
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    rules() {
      return {
        clientId: [
          {
            required: true,
            max: 64,
            message: this.$t("PLACEENTER") + 64 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        clientSecret: [
          {
            required: true,
            max: 128,
            message: this.$t("PLACEENTER") + 128 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        scope: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        authorizedGrantTypes: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        accessTokenValidity: [
          {
            required: true,
            max: 11,
            message: this.$t("PLACEENTER") + 11 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        refreshTokenValidity: [
          {
            required: true,
            max: 11,
            message: this.$t("PLACEENTER") + 11 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        autoapprove: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
    queryFormItem() {
      return {
        clientId: {
          label: this.$t("CLIENT_ID"),
        },
      };
    },
    // 表格配置
    tableColumns() {
      return [
        // 客户端 id
        {
          dataIndex: "clientId",
          title: () => this.$t("CLIENT_ID"),
          width: 200,
        },
        // 客户端秘钥
        {
          dataIndex: "clientSecret",
          ellipsis: true,
          sorter: false,
          title: () => this.$t("CLIENT_SECRET"),
          minWidth: 400,
        },
        // 	权限范围
        {
          dataIndex: "scope",
          sorter: false,
          title: () => this.$t("SCOPE"),
          width: 200,
        },
        // 	授权类型
        {
          dataIndex: "authorizedGrantTypes",
          ellipsis: true,
          sorter: false,
          title: () => this.$t("AUTH_TYPE"),
          width: 200,
        },
        // 是否自动授权
        {
          dataIndex: "autoapprove",
          sorter: false,
          scopedSlots: { customRender: "autoapprove" },
          title: () => this.$t("AUTO_APPROVE"),
          width: 150,
        },
        // token有效期
        {
          dataIndex: "accessTokenValidity",
          sorter: false,
          title: () => this.$t("TOKEN_VALIDITY"),
          width: 300,
        },
        // token刷新有效期
        {
          dataIndex: "refreshTokenValidity",
          sorter: false,
          title: () => this.$t("REFRESH_TOKEN_VALIDITY"),
          width: 300,
        },
        // 	授权模式
        {
          dataIndex: "authorities",
          ellipsis: true,
          sorter: false,
          title: () => this.$t("AUTH_MODEL"),
          width: 350,
        },
        // 	资源IDs
        {
          dataIndex: "resourceIds",
          sorter: false,
          title: () => this.$t("RESOURCE_ID"),
          width: 300,
        },
        // 	重定向地址
        {
          dataIndex: "webServerRedirectUri",
          ellipsis: true,
          sorter: false,
          title: () => this.$t("REDIRECTION_ADDRESS"),
          width: 260,
        },
        // 	附加信息
        {
          dataIndex: "additionalInformation",
          sorter: false,
          title: () => this.$t("ADDITIONAL_INFO"),
          width: 300,
        },
      ];
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 初始化数据
    init() {
      // 获取是否数据字典
      this.getDictByCode(`DIC:COMMON:WHETHER_BOOLEAN`).then((res) => {
        if (res.data.data && res.data.data.length > 0) {
          this.form.autoapprove = res.data.data[0].value;
          this.yesNoList = res.data.data;
        }
      });
      // this.searchPageData()
    },
    // 分页查询列表数据
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/oauth-client-details/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 点击新增
    handleAdd() {
      this.drawerVisible = true;
      this.form.id = "";
      this.form.clientId = "";
      this.form.clientSecret = "";
      this.form.scope = "all";
      this.form.authorizedGrantTypes = [];
      this.form.refreshTokenValidity = "";
      this.form.accessTokenValidity = "";
      this.form.autoapprove = "";
      this.form.authorities = "";
      this.form.resourceIds = "";
      this.form.webServerRedirectUri = "";
      this.form.additionalInformation = "";
      this.title = this.$t("ADD");
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.form.id = row.id;
      this.form.clientId = row.clientId;
      this.form.clientSecret = row.clientSecret;
      this.form.scope = row.scope;
      if (row.authorities) {
        this.form.authorities = row.authorities;
      }
      this.form.autoapprove = row.autoapprove;
      if (row.accessTokenValidity) {
        this.form.accessTokenValidity = row.accessTokenValidity.toString();
      }
      if (row.refreshTokenValidity) {
        this.form.refreshTokenValidity = row.refreshTokenValidity.toString();
      }
      if (row.authorizedGrantTypes) {
        this.form.authorizedGrantTypes = row.authorizedGrantTypes.split(",");
      }
      this.form.resourceIds = row.resourceIds;
      this.form.webServerRedirectUri = row.webServerRedirectUri;
      this.form.additionalInformation = row.additionalInformation;
      this.title = this.$t("EDIT");
      this.drawerVisible = true;
    },
    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/oauth-client-details/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"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/sys/oauth-client-details/${row.id}`
            )
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 点击弹框的保存
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const params = { ...this.form };
          if (params.authorizedGrantTypes.length > 0) {
            params.authorizedGrantTypes = params.authorizedGrantTypes.join(",");
          }
          if (this.form.id) {
            this.$axios
              .put(
                `${ApiConstant.PREFIX_CORE}/api/sys/oauth-client-details`,
                params
              )
              .then((res) => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.handleCancel();
              });
          } else {
            this.$axios
              .post(
                `${ApiConstant.PREFIX_CORE}/api/sys/oauth-client-details`,
                params
              )
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.handleCancel();
              });
          }
        }
      });
    },
    // 取消
    handleCancel() {
      this.drawerVisible = false;
    },
  },
};
</script>
