<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="授权码" prop="secretKey">
        <el-input
          v-model="queryParams.secretKey"
          placeholder="请输入授权码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="secretList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="项目名称" align="center" prop="projectName"/>
      <el-table-column label="状态" align="center" prop="statusText"/>
      <el-table-column label="过期时间" align="center" property="date" prop="overdueDate"/>
      <el-table-column label="授权码" align="center" prop="secretKey"/>
      <el-table-column label="授权认证类型" align="center" prop="authorityType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_status" :value="scope.row.authorityType"/>
        </template>
      </el-table-column>
      <el-table-column label="是否校验授权" align="center" prop="isSwitch">
        <template slot-scope="scope">
          <el-switch
            v-if="scope.row.authorityType==1"
            @change="switchChange(scope.row.isSwitch,scope.row.id)"
            v-model="scope.row.isSwitch"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--          >修改-->
          <!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="againUpdate(scope.row)"
          >重新授权
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.authorityType==1"
            @click="handleClose(scope.row)"
          >关闭授权
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCopy(scope.row)"
          >复制授权码
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="项目名称" prop="projectName">
          <el-select v-model="form.projectName" filterable placeholder="请选择项目名称" @change="onChange">
            <el-option
              v-for="item in projectData"
              :key="item.id"
              :label="item.projectName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="overdueDate">
          <el-date-picker
            v-model="form.overdueDate"
            placeholder="请选择过期时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="授权认证类型" prop="authorityType">
          <el-select v-model="form.authorityType" placeholder="授权认证类型">
            <el-option
              v-for="dict in dict.type.sys_is_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </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>
    <!-- 删除项目授权管理对话框 -->
    <el-dialog title="系统提示" :visible.sync="openDel" width="500px" append-to-body>
      <h>此项目已经和授权码成功绑定，如想要删除，请在下方输入框中输入"确认删除"！</h>
      <el-form ref="form" :model="formDel" label-width="120px">
        <!--        <el-form-item label="请输入确认删除" prop="inputConfirm">-->
        <el-input style="margin-top: 8px;" v-model="formDel.inputConfirm" placeholder="确认删除"/>
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormDel">确 定</el-button>
        <el-button @click="cancelDel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSecret,
  getSecret,
  delSecret,
  addSecret,
  updateSecret,
  updateIsSwitch,
  closeAuthority
} from "@/api/system/secret";
import {listAllProject} from "@/api/system/project";

export default {
  name: "secret",
  dicts: ['sys_is_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目授权管理表格数据
      secretList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDel: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        secretKey: null
      },
      projectData: [],
      // 表单参数
      form: {},
      formDel: {
        inputConfirm: ''
      },
      value: true,
      // 表单校验
      rules: {
        authorityType: [{required: true, message: "授权认证类型不能为空", trigger: "change"}],
        overdueDate: [{required: true, message: "过期时间不能为空", trigger: "change"}],
        projectName: [{required: true, message: "项目名称不能为空", trigger: "change"}]
      },
    };
  },
  created() {
    this.getList();
    this.getProjectList()
  },
  methods: {
    // 任务组名字典翻译
    jobGroupFormat(row, column) {
      return this.selectDictLabel(this.dict.type.sys_is_status, row.authorityType);
    },
    handleClose(row) {
      let params = {
        id: row.id,
        projectName: row.projectName
      }
      this.$modal.confirm('是否确认关闭项目名称为"' + row.projectName + '"的授权？').then(function () {
        return closeAuthority(params);
      }).then((res) => {
        this.$modal.msgSuccess("关闭成功");
        this.getList();
        this.getProjectList();
      }).catch(() => {
      });
    },
    switchChange(val, id) {
      console.log(val, id);
      let params = {
        id: id,
        isSwitch: val
      }
      updateIsSwitch(params).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
        this.getProjectList();
      });
    },
    /** 查询项目授权管理列表 */
    getList() {
      this.loading = true;
      listSecret(this.queryParams).then(response => {
        this.secretList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询项目管理列表 */
    getProjectList() {
      this.loading = true;
      listAllProject().then(response => {
        this.projectData = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        authorityType: null,
        overdueDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getProjectList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目授权管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSecret(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目授权管理";
      });
    },
    //重新授权
    againUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSecret(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目授权管理";
      });
    },
    /** 复制授权码按钮操作 */
    handleCopy(row) {
      const secretKey = row.secretKey;
      navigator.clipboard.writeText(secretKey)
        .then(() => {
          this.$message.success("信息已复制");
        })
        .catch(err => {
          console.error("复制授权码操作失败: ", err);
        });
    },
    onChange(e) {
      this.form.projectId = e
      this.form.projectName = this.projectData.find(item => item.id == e).projectName
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSecret(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getProjectList();
            });
          } else {
            addSecret(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getProjectList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.ids = row.id || this.ids;
      this.formDel.inputConfirm = ''
      this.openDel = true
    },
    submitFormDel() {
      if (this.formDel.inputConfirm == '确认删除') {
        delSecret(this.ids).then(() => {
          this.ids = []
          this.getList();
          this.getProjectList();
          this.formDel.inputConfirm = ''
          this.openDel = false
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      } else {
        this.$message.error("您输入的内容不正确，请重新输入！")
      }
    },
    cancelDel() {
      this.formDel.inputConfirm = ''
      this.openDel = false
    },
  }
};
</script>
