<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline"
            v-if="checkPermission(['oauth2Client:add'])" @click="handleAdd">添加</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" placeholder="请输入客户端名称" @advancedSearch="advancedSearchEvent" advanced>
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="客户端id">
                  <el-input v-model="advancedForm.client_id" placeholder="请输入客户端Id" clearable></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status">
                    <el-option :key="0" label="正常" :value="0" />
                    <el-option :key="1" label="禁用" :value="1" />
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column prop="name" label="客户端名称" />
        <el-table-column prop="client_id" label="客户端id" />
        <el-table-column prop="status" label="状态" >
          <template slot-scope="scope">
            {{ scope.row.status === 0 ? '正常' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">{{ scope.row.create_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" v-if="checkPermission(['oauth2Client:edit'])"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger"
              v-if="checkPermission(['oauth2Client:delete'])"
              @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog :title="editForm.id ? '编辑' : '添加'" :visible.sync="dialogVisible" width="600px"
      @open="handleDialogOpen" :modal-append-to-body="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="editForm" :rules="formRules" ref="editForm" label-width="125px">
        <el-form-item label="客户端名称" prop="name">
          <el-input v-model="editForm.name" :maxlength="20" placeholder="请输入客户端名称"></el-input>
        </el-form-item>
        <el-form-item label="客户端id" prop="client_id">
          <el-input v-model="editForm.client_id" placeholder="请输入客户端id" :disabled="editForm.id">
            <template slot="append" v-if="!editForm.id">
              <el-button @click="randomClientId()">随机生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="客户端secret" prop="secret">
          <el-input v-model="editForm.secret" placeholder="请输入客户端secret">
            <template slot="append">
              <el-button @click="randomSecret()">随机生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="访问令牌时效(s)" prop="access_token_validity_seconds">
          <el-input type="number" v-model="editForm.access_token_validity_seconds" placeholder="请输入访问令牌有效期（秒）"></el-input>
        </el-form-item>
        <el-form-item label="刷新令牌时效(s)" prop="refresh_token_validity_seconds">
          <el-input type="number" v-model="editForm.refresh_token_validity_seconds" placeholder="请输入刷新令牌有效期（秒）"></el-input>
        </el-form-item>
        <el-form-item label="授权类型" prop="authorized_grant_types">
          <el-select v-model="editForm.authorized_grant_types" placeholder="请选择授权类型" multiple style="width: 100%;">
            <el-option label="密码模式" value="password"/>
            <el-option label="授权码模式" value="authorization_code"/>
            <el-option label="简化模式" value="implicit"/>
            <el-option label="客户端模式" value="client_credentials"/>
            <el-option label="刷新模式" value="refresh_token"/>
          </el-select>
        </el-form-item>
        <el-form-item label="可重定向的uri" prop="redirect_uris" v-if="showRedirectUris()">
          <el-input v-model="editForm.redirect_uris" placeholder="请输入可重定向的uri地址，多个地址逗号隔开"></el-input>
        </el-form-item>
        <el-form-item label="授权范围" prop="scopes" v-if="showScopes()">
          <el-input v-model="editForm.scopes" placeholder="请输入授权范围，多个授权逗号隔开"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
                    placeholder="请输入客户端描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_OAuth2Client from '@/api/oauth2Client'
export default {
  name: 'oauth2Client',
  data() {
    return {
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 列表数据
      tableData: '',
      // 添加/编辑表单
      editForm: {
        secret: ''
      },
      advancedForm: {

      },
      // 添加|编辑 表单规则
      formRules: {
        name: [
          this.MixinRequired('客户端名称必填！')
        ],
        client_id: [
          this.MixinRequired('客户端id必填！')
        ],
        secret: [
          this.MixinRequired('客户端secret必填！')
        ],
        status: [
          this.MixinRequired('客户端状态必填！')
        ],
        access_token_validity_seconds: [
          this.MixinRequired('访问令牌时效必填！')
        ],
        refresh_token_validity_seconds: [
          this.MixinRequired('刷新令牌时效必填！')
        ],
        authorized_grant_types: [
          this.MixinRequired('授权类型必填！')
        ],
        redirect_uris: [
          this.MixinRequired('可重定向uri必填！')
        ]
      },
      // 是否显示 添加|编辑 表单
      dialogVisible: false
    }
  },
  watch: {
  },
  mounted() {
    this.GET_List()
  },
  methods: {
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      this.params.page_no = 1
      this.GET_List()
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_List()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_List()
    },

    /** 添加弹窗 */
    handleAdd() {
      this.editForm = {
        status: 0
      }
      this.dialogVisible = true
    },

    /** 编辑弹窗 */
    handleEdit(row) {
      this.editForm = this.MixinClone(row)
      this.editForm.redirect_uris = this.editForm.redirect_uris ? this.editForm.redirect_uris.join(',') : ''
      this.editForm.scopes = this.editForm.scopes ? this.editForm.scopes.join(',') : ''
      this.dialogVisible = true
    },
    /** 删除 */
    handleDelete(id) {
      this.$confirm('确定要删除吗？', '提示', { type: 'warning' }).then(() => {
        API_OAuth2Client.del(id).then(() => {
          this.$message.success('删除成功！')
          this.GET_List()
        })
      }).catch(() => { })
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => { this.$refs['editForm'].clearValidate() })
    },

    /** 提交 添加|编辑 表单 */
    submitEditForm() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          const { id } = this.editForm
          const data = this.MixinClone(this.editForm)
          if (data.redirect_uris) {
            data.redirect_uris = data.redirect_uris.split(',')
          }
          if (data.redirect_uris === '') {
            data.redirect_uris = []
          }
          if (data.scopes) {
            data.scopes = data.scopes.split(',')
          }
          if (data.scopes === '') {
            data.scopes = []
          }
          if (id) {
            API_OAuth2Client.edit(id, data).then(response => {
              this.dialogVisible = false
              this.$message.success('修改成功！')
              this.GET_List()
            })
          } else {
            API_OAuth2Client.add(data).then(() => {
              this.dialogVisible = false
              this.$message.success('添加成功！')
              this.GET_List()
            })
          }
        } else {
          return false
        }
      })
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        name: data
      }
      this.params.page_no = 1
      this.GET_List()
    },

    /** 查询分页列表 */
    GET_List() {
      this.loading = true
      API_OAuth2Client.getList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    },

    /** 是否显示重定向地址 */
    showRedirectUris() {
      return this.editForm.authorized_grant_types &&
        this.editForm.authorized_grant_types.some((item) => item === 'authorization_code' || item === 'implicit')
    },

    /** 是否显示授权范围 */
    showScopes() {
      return this.editForm.authorized_grant_types &&
        this.editForm.authorized_grant_types.some((item) => item === 'password' || item === 'authorization_code' || item === 'implicit')
    },

    /** 随机生成客户端id */
    randomClientId() {
      this.$set(this.editForm, 'client_id', this.generateRandom(10))
    },

    /** 随机生成密钥 */
    randomSecret() {
      this.$set(this.editForm, 'secret', this.generateRandom(30))
    },

    generateRandom(length) {
      const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
      let randomID = ''

      for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length)
        randomID += characters.charAt(randomIndex)
      }

      return randomID
    }

  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

.birthday{
  width: 94%;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
