<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="飞书账号" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入飞书账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="appId" prop="appId">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入appId"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:feishuConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:feishuConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:feishuConfig:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="飞书账号" align="center" prop="name" />
      <el-table-column label="appId" align="center" prop="appId" min-width="160" show-overflow-tooltip />
      <el-table-column label="appSecret" align="center" prop="appSecret" min-width="180" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="170" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="170" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:feishuConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:feishuConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="飞书账号" prop="name">
          <el-input v-model="form.name" placeholder="请输入飞书账号名称" />
        </el-form-item>
        <el-form-item label="appId" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入飞书应用 AppId" />
        </el-form-item>
        <el-form-item label="appSecret" prop="appSecret">
          <el-input v-model="form.appSecret" placeholder="请输入飞书应用 AppSecret" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限导入示例">
          <el-input
            :value="permissionImportExample"
            type="textarea"
            :rows="12"
            readonly
            class="permission-example"
          />
          <el-button type="primary" plain size="mini" icon="el-icon-document-copy" style="margin-top: 8px" @click="copyPermissionExample">
            一键复制
          </el-button>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFeishuConfig,
  getFeishuConfig,
  addFeishuConfig,
  updateFeishuConfig,
  delFeishuConfig
} from '@/api/course/feishuConfig'

export default {
  name: 'FeishuConfig',
  data() {
    return {
      loading: false,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      list: [],
      title: '',
      open: false,
      statusOptions: [
        { label: '正常', value: 1 },
        { label: '停用', value: 0 },
        { label: '已封禁', value: -1 }
      ],
      permissionImportExample: `{
  "scopes": {
    "tenant": [
      "docs:permission.setting:read",
      "docs:permission.setting:write_only",
      "docx:document",
      "drive:drive",
      "space:document:delete"
    ],
    "user": []
  }
}`,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        appId: null,
        status: null
      },
      form: {},
      rules: {
        name: [{ required: true, message: '飞书账号不能为空', trigger: 'blur' }],
        appId: [{ required: true, message: 'appId不能为空', trigger: 'blur' }],
        appSecret: [{ required: true, message: 'appSecret不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listFeishuConfig(this.queryParams).then(response => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    reset() {
      this.form = {
        id: null,
        name: null,
        appId: null,
        appSecret: null,
        status: 1,
        remark: null
      }
      this.resetForm('form')
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增飞书配置'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getFeishuConfig(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改飞书配置'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const req = this.form.id != null ? updateFeishuConfig(this.form) : addFeishuConfig(this.form)
        req.then(response => {
          if (response.code !== 200) {
            this.msgError(response.msg)
            return
          }
          this.msgSuccess(this.form.id != null ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除飞书配置编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delFeishuConfig(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    },
    getStatusLabel(status) {
      const map = { 1: '正常', 0: '停用', [-1]: '已封禁' }
      return map[status] || '未知'
    },
    statusTagType(status) {
      if (status === 1) return 'success'
      if (status === 0) return 'warning'
      if (status === -1) return 'danger'
      return 'info'
    },
    copyPermissionExample() {
      navigator.clipboard.writeText(this.permissionImportExample).then(() => {
        this.msgSuccess('已复制到剪贴板')
      }).catch(() => {
        this.msgError('复制失败，请手动复制')
      })
    }
  }
}
</script>

<style scoped>
.permission-example >>> textarea {
  font-family: Consolas, Monaco, monospace;
  background-color: #f5f7fa;
  color: #606266;
  cursor: default;
}
</style>
