<template>
  <div class="app-container">
    <addModal ref="addModel" @success="modalSuccess" />
    <downloadDoc ref="downloadDoc"/>
    <div style="margin-bottom: 20px">
      <el-button
        class="filter-item"
        style="margin-right: 20px"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加服务权限
      </el-button>
      <el-select
        v-model="form.purchaserId"
        placeholder="请选择购买方"
        clearable
        filterable
      >
        <el-option
          v-for="(item, index) in buyList"
          :key="index"
          :label="item.companyName"
          :value="item.purchaserId"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        style="margin-left: 20px"
        icon="el-icon-search"
        @click="query"
      >
        搜索
      </el-button>

      <el-button
        class="el-icon-download"
        type="primary"
        plain
        @click="openDownload"
      >
        下载开发文档
      </el-button>
    </div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{
            (pagination.current - 1) * pagination.pageSize + (scope.$index + 1)
          }}
        </template>
      </el-table-column>
      <el-table-column label="购买方">
        <template slot-scope="scope">
          {{ scope.row.purchaserName }}
        </template>
      </el-table-column>
      <el-table-column label="条件接口类型">
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.interfaceTypeDesc" :key="index">{{ item  }}{{scope.row.interfaceTypeDesc.length >=index+1?'':'，'}}</span>

        </template>
      </el-table-column>
      <el-table-column label="调用次数">
        <template slot-scope="scope">
          {{ scope.row.hadReqTimes }}
        </template>
      </el-table-column>
      <el-table-column label="总调用次数">
        <template slot-scope="scope">
          {{ scope.row.limitTimes }}
        </template>
      </el-table-column>
      <el-table-column label="调用频率">
        <template slot-scope="scope">
          {{ scope.row.limitFrequency }}次/{{ scope.row.limitFrequencyTime }}秒
        </template>
      </el-table-column>
      <el-table-column label="是否返回详细信息">
        <template slot-scope="scope">
          <el-tag
            type="primary"
            effect="plain"
            v-if="scope.row.resultInfoSwitch"
          >
            是
          </el-tag>
          <el-tag type="info" effect="plain" v-if="!scope.row.resultInfoSwitch">
            否
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        class-name="status-col"
        width="100"
      >
        <template slot-scope="{ row }">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusFilterStr }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="350"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
          <template>
            <el-button
              v-if="row.status"
              size="mini"
              type="danger"
              @click="statusChange(row, false)"
              >停用</el-button
            >
            <el-button
              v-else
              size="mini"
              type="danger"
              @click="statusChange(row, true)"
              >启用</el-button
            >
            <el-button type="primary" size="mini" @click="uploadSecretKey(row)">
              下载密钥
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="pagination.total"
      :page.sync="pagination.current"
      :limit.sync="pagination.pageSize"
      :page-sizes="pagination.pageSizeOptions"
      :layout="pagination.layout"
      @pagination="handleSizeChange"
    />
  </div>
</template>

<script>
import AddModal from "./modal/serviceAddModal.vue";
import downloadDoc from "./modal/downloadDoc.vue";
import tableMixins from "@/mixins/tableMixins";
import { authPage, authdel, authDisable, authEnable } from "@/api/tripartiteApi";
import { purchaserList } from "@/api/configuration";
import Pagination from "@/components/Pagination";
import { saveAs } from "file-saver";
export default {
  components: { Pagination, AddModal ,downloadDoc},
  filters: {
    statusFilter(status) {
      return status ? "success" : "info";
    },
    statusFilterStr(status) {
      return status ? "已启用" : "已停用";
    },
  },
  mixins: [tableMixins],
  data() {
    return {
      form: {},
      buyList: [],
    };
  },
  methods: {
    initData() {
      this.getTableList();
      this.purchaserList();
    },
    openDownload(){
      this.$refs.downloadDoc.open();
    },
    // 获取表格数据
    async getTableList() {
      this.tableLoading = true;
      try {
        const result = await authPage(this.getFilterParams());
        this.setDataList(result.data);
      } catch (e) {
        console.log(e);
      } finally {
        this.tableLoading = false;
      }
    },
    // 获取筛选信息
    query() {
      this.clearPageParams();
      this.getTableList();
    },
    // 增加筛选条件
    transformFilterForm() {
      return {
        purchaserId: this.form.purchaserId || null,
      };
    },
    modalSuccess(isEdit) {
      if (!isEdit) {
        this.clearPageParams();
      }
      this.getTableList();
    },
    handleCreate() {
      this.$refs.addModel.open();
    },
    handleUpdate(row) {
      this.$refs.addModel.open(Object.assign({}, row));
    },
    statusChange(row, status) {
      const that = this;
      this.$confirm(
        `确定 ${status ? "启用授权" : "停用授权"} 操作吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showClose: false,
          type: "warning",
          beforeClose: async (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.confirmButtonText = "提交中...";
              try {
                if (status) {
                  await authEnable(row.id);
                } else {
                  await authDisable(row.id);
                }
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                that.getTableList();
              } catch (e) {
                // this.$message({
                //   type: 'error',
                //   message: '删除失败!'
                // })
              } finally {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  instance.cancelButtonLoading = false;
                }, 300);
              }
            } else {
              done();
            }
          },
        }
      )
        .then(() => {})
        .catch(() => {});
    },
    handleDelete(row, index) {
      const that = this;
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.cancelButtonLoading = true;
            instance.confirmButtonText = "提交中...";
            try {
              await authdel(row.id);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              that.getTableList();
            } catch (e) {
              // this.$message({
              //   type: 'error',
              //   message: '删除失败!'
              // })
            } finally {
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
                instance.cancelButtonLoading = false;
              }, 300);
            }
          } else {
            done();
          }
        },
      })
        .then(() => {})
        .catch(() => {});
    },
    uploadSecretKey(row) {
      let str = `appId: ${row.appId}\r\nappKey: ${row.appKey}\r\nappSecret: ${row.appSecret}\r\nprivateKey: ${row.privateKey}`;
      let strData = new Blob([str], { type: "text/plain;charset=utf-8" });
      saveAs(strData, "密钥.txt");
    },
    // 购买方列表
    purchaserList() {
      purchaserList().then((res) => {
        this.buyList = res.data;
      });
    },
  },
};
</script>
