<template>
  <div>
    <div>
      <el-form :inline="true" class="orderform" size="mini">
        <el-row>
          <el-form-item label="应用名称:">
            <el-input v-model="tag" style="width: 250px" placeholder="请输入应用名称" class="search_tag" clearable/>
          </el-form-item>
          <el-form-item label="应用状态:">
            <el-select
              v-model="status"
              clearable
              placeholder="请选择"
              style="width: 250px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="应用类型:">
            <el-select v-model="appTypeId" clearable filterable placeholder="请选择应用类型">
              <el-option
                v-for="item in appTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="btn_search()"><i class="el-icon-search"/> 搜索</el-button>
            <el-button @click="btn_clear()"><i class="el-icon-remove-outline"/> 重置</el-button>
            <!--el-button type="primary" @click="addFormVisible = true"><i class="el-icon-plus"/> 添加</el-button-->
          </el-form-item>
        </el-row>
      </el-form>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :highlight-current-row="true"
        :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
        border>
        <el-table-column
          prop="id"
          label="AppId"/>
        <el-table-column
          prop="name"
          label="应用名称"/>
        <el-table-column
          prop="appType.name"
          label="应用类型"/>
        <el-table-column
          prop="user.name"
          label="开发者"/>
        <el-table-column
          prop="apiKey"
          label="API Key"/>
        <el-table-column
          prop="secretKey"
          label="Secret Key"/>
        <el-table-column
          :formatter="formatStatus"
          prop="status"
          label="应用状态"/>
        <el-table-column
          prop="createTime"
          label="创建时间"/>
        <el-table-column
          label="操作" width="150px">
          <template slot-scope="scope">
            <el-badge v-if="scope.row.status == 99" value="可审核" style="margin-top: 10px;">
              <el-button type="text" @click="handleViewAuth(scope.row)">审核接口权限</el-button>
            </el-badge>
            <el-button v-else type="text" @click="handleViewAuth(scope.row)">查看接口权限</el-button>
            <el-button v-if="scope.row.status == 2" type="text" @click="handleDisable(scope.row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mydiv">
        <el-pagination
          :current-page.sync="pageNo"
          :page-sizes="[10, 50, 100, 300,1000]"
          :page-size="pageSize"
          :total="totalDataNumber"
          layout="sizes,total, prev, pager, next"
          class="table-pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>

    </div>

    <el-dialog
      :visible.sync="disableFormVisible"
      title="审核提示"
      width="30%">
      <span>审核应用</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submitDisable(3)">拒 绝</el-button>
        <el-button type="primary" @click="submitDisable(1)">通 过</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="showAppApis"
      :title="appName"
      width="70%"
      @close="btn_search">
      <!-- <p>应用接口权限列表:</p> -->
      <div style="display: flex;justify-content: space-between;margin: 10px 0; align-items: center;">
        <div>
          应用接口权限列表:
        </div>
        <div v-if="selectAllList.length>0">
          <el-button type="primary" plain size="mini" @click="selectAllClick(1)">批量通过</el-button>
          <el-button type="danger" plain size="mini" @click="selectAllClick(2)">批量拒绝</el-button>
        </div>
      </div>
      <el-table
        :data="authData"
        :highlight-current-row="true"
        :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
        fit
        border
        @selection-change="handleSelectionChange">
        <el-table-column
          :selectable="row=> row.status == 0 && appStatus ==1 || appStatus == 99 "
          type="selection"
          width="55"
        />
        <el-table-column
          prop="api.name"
          label="API"/>
        <el-table-column
          prop="api.url"
          label="请求地址"/>
        <!-- <el-table-column
          prop="callLimit"
          label="调用限制量">
          <template slot-scope="scope">
            <el-input :disabled="appStatus ==3 || appStatus == 2 || appStatus == 0" v-model="scope.row.callLimit" type="number" size="mini" @blur="inputChange(scope.row,1)" />
          </template>
        </el-table-column> -->
        <el-table-column
          prop="qpsLimit"
          label="QPS限制">
          <template slot-scope="scope">
            <el-input :disabled="appStatus ==3 || appStatus == 2 || appStatus == 0" v-model="scope.row.qpsLimit" type="number" size="mini" oninput="value=value.replace(/[^0-9.]/g,'')" @blur="inputChange(scope.row,2)" />
          </template>
        </el-table-column>
        <el-table-column
          prop="enable"
          width="200"
          label="接口使用状态" align="center">
          <template slot-scope="scope">
            <el-switch
              :disabled="appStatus ==3 || appStatus == 2 || appStatus == 0"
              v-model="scope.row.enable"
              :active-value="0"
              :inactive-value="1"
              active-color="#13ce66"
              inactive-color="#909399"
              active-text="启用"
              inactive-text="停用"
              size="mini"
              @change="handleEnable(scope.row.id,$event,scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column
          label="接口申请状态"
          width="150" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === 0" type="text">待审核</el-button>
            <el-button v-else-if="scope.row.status === 1" type="text">已申请</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template slot-scope="scope">
            <div v-if="scope.row.status === 0">
              <el-button :disabled="appStatus ==3 || appStatus == 2 || appStatus == 0" type="text" @click="handleEdit(scope.row.id,1)">通过</el-button>
              <el-button :disabled="appStatus ==3 || appStatus == 2 || appStatus == 0" type="text" @click="handleEdit(scope.row.id,2)">拒绝</el-button>
            </div>

          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          :current-page.sync="pageAuthNo"
          :page-sizes="[10, 50, 100, 300,1000]"
          :page-size="pageAuthSize"
          :total="totalAuthDataNumber"
          layout="sizes,total, prev, pager, next"
          class="table-pagination"
          @size-change="handleAuthSizeChange"
          @current-change="handleAuthCurrentChange"/>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios'
import APP_CONFIG from "../../../public/config";

export default {
  name: 'Index',
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  data() {
    return {
      tag: '',
      select_value: '', // 用户状态
      options: [
        {
          value: '',
          label: '全部'
        }, {
          value: 0,
          label: '停用'
        }, {
          value: 1,
          label: '正常'
        }, {
          value: 2,
          label: '应用待审核'
        }, {
          value: 3,
          label: '审核被拒绝'
        }],
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      allAuthData: [], // app接口权限
      authData: [], // app接口权限
      pageAuthNo: 1, // app接口权限
      totalAuthDataNumber: 0, // app接口权限
      pageAuthSize: 10, // app接口权限
      formLabelWidth: '100px', // 弹出框form宽
      disableFormVisible: false,
      addFormVisible: false,
      editFormVisible: false,
      showAppApis: false,
      addForm: {
        name: '',
        url: '',
        callLimit: '',
        qpsLimit: '',
        apiTypeId: '',
        description: ''
      },
      editForm: {
        id: '',
        name: '',
        apiTypeId: '',
        description: ''
      },
      status: '',
      id: '',
      apiTypes: [],
      appTypeId: '', // 应用类型id
      appTypes: [],
      appStatus: null,
      appName: '',
      selectAllList: [] // 全选列表
    }
  },
  async created() {
    this.searchAllApiTypes()
    await this.searchAllAppTypes()
    this.btn_search()
  },
  methods: {
    selectAllClick(status) {
      const vm = this
      if (status === 1) {
        vm.$confirm('此操作将批量审核，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          vm.selectAll(status)
        })
      } else {
        vm.$confirm('此操作将批量拒绝，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          vm.selectAll(status)
        })
      }
    },
    selectAll(status) {
      const vm = this
      vm.selectAllList.forEach((val, index) => {
        const params = new URLSearchParams()
        params.append('appApiId', val)
        params.append('status', status)
        axios.post(process.env.BASE_API + '/appapi/editAppApiStatus', params).then(res => {
          if (res.data.code === 10000) {
            if (vm.selectAllList.length === index + 1) {
              if (status === 1) {
                vm.$message({
                  message: '批量审核成功',
                  type: 'success'
                })
              } else {
                vm.$message({
                  message: '批量拒绝成功',
                  type: 'success'
                })
              }
              vm.getAppApi()
            }
          }
        })
      })
    },
    handleSelectionChange(e) {
      if (e.length > 0) {
        this.selectAllList = e.map(val => {
          return val.id
        })
      } else {
        this.selectAllList = []
      }
    },
    searchAllAppTypes() {
      const vm = this
      axios.get(process.env.BASE_API + '/apptype/list', {}).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.appTypes = []
        } else {
          vm.appTypes = obj.data
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    inputChange(item, num) {
      if (item.qpsLimit === '') {
        return this.$message.error('QPS限制不能为空')
      }
      const params = new URLSearchParams()
      params.append('id', item.id)
      params.append('callLimit', item.callLimit)
      params.append('qpsLimit', item.qpsLimit)
      const vm = this
      if (num === 1) {
        vm.$confirm('是否将调用限制量修改为:' + item.callLimit, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.post(process.env.BASE_API + '/appapi/update', params).then(function(response) {
            var obj = response.data
            if (obj.code === 10000) {
              vm.$message({
                message: '更新成功',
                type: 'success'
              })
              vm.getAppApi()
            }
          })
        })
      } else {
        vm.$confirm('是否将QPS限制修改为:' + item.qpsLimit, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.post(process.env.BASE_API + '/appapi/update', params).then(function(response) {
            var obj = response.data
            if (obj.code === 10000) {
              vm.$message({
                message: '更新成功',
                type: 'success'
              })
              vm.getAppApi()
            }
          })
        })
      }
    },
    handleEnable(id, e, row) {
      if (e === 0) {
        this.$confirm('此操作将启用该接口，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.enable(id, e)
        }).catch(() => {
          row.enable = 1
        })
      } else {
        this.$confirm('此操作将停用该接口，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.enable(id, e)
        }).catch(() => {
          row.enable = 0
        })
      }
    },
    enable(id, enable) {
      const params = new URLSearchParams()
      params.append('appApiId', id)
      params.append('enable', enable)
      axios.post(process.env.BASE_API + '/appapi/editAppApiEnable', params).then(res => {
        if (res.data.code === 10000) {
          if (enable === 0) {
            this.$message({
              message: '启用成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '停用成功',
              type: 'success'
            })
          }
          this.getAppApi()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    formatStatus(ob) {
      if (ob.status === 1) {
        return '正常'
      } else if (ob.status === 0) {
        return '停用'
      } else if (ob.status === 2) {
        return '应用待审核'
      } else if (ob.status === 3) {
        return '审核被拒绝'
      } else if (ob.status === 99) {
        return '有待审接口'
      }
    },
    searchAllApiTypes() {
      const vm = this
      axios.get(process.env.BASE_API + '/apitype/list', {
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.totalDataNumber = 0
          vm.apiTypes = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.apiTypes = obj.data
          } else {
            vm.apiTypes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_search() {
      const vm = this
      axios.get(process.env.BASE_API + '/app/list', {
        params: {
          tag: this.tag,
          status: this.status,
          appTypeId: this.appTypeId
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.totalDataNumber = 0
          vm.allData = []
          vm.tableData = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.allData = obj.data
            vm.tableData = obj.data.slice(0, vm.pageSize)
          } else {
            vm.allData = []
            vm.tableData = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_clear() {
      this.tag = ''
      this.select_value = ''
      this.btn_search()
    },
    handleCurrentChange() {
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleAuthCurrentChange() {
      this.authData = this.allAuthData.slice((this.pageAuthNo - 1) * this.pageAuthSize, this.pageAuthNo * this.pageAuthSize)
    },
    handleAuthSizeChange(val) {
      this.pageAuthSize = val
      this.authData = this.allAuthData.slice((this.pageAuthNo - 1) * this.pageAuthSize, this.pageAuthNo * this.pageAuthSize)
    },
    btnAddCancel() {
      this.addFormVisible = false
      this.addForm.name = ''
      this.addForm.description = ''
    },
    handleEdit(appid, status) {
      if (status === 1) {
        this.$confirm('此操作将通过审核，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.examine(appid, status)
        })
      } else {
        this.$confirm('此操作将驳回审核，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.examine(appid, status)
        })
      }
    },
    examine(id, status) {
      const params = new URLSearchParams()
      params.append('appApiId', id)
      params.append('status', status)
      axios.post(process.env.BASE_API + '/appapi/editAppApiStatus', params).then(res => {
        if (res.data.code === 10000) {
          if (status === 1) {
            this.$message({
              message: '审核成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '拒绝成功',
              type: 'success'
            })
          }

          this.getAppApi()
        } else {
          this.$message({
            message: '审核失败',
            type: 'error'
          })
          this.getAppApi()
        }
      })
    },
    btnUpdateCancel() {
      this.editFormVisible = false
      this.editForm.name = ''
      this.editForm.description = ''
    },
    btnUpdateSubmit() {
      if (this.editForm.name === '' || this.editForm.name === undefined) {
        this.$message.info('请输入接口类型名称，不能为空')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.editForm.id)
      params.append('name', vm.editForm.name)
      params.append('description', vm.editForm.description)
      axios.post(process.env.BASE_API + '/apimngr/update', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.editForm.name = ''
          vm.editForm.description = ''
          vm.editFormVisible = false
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleDisable(row) {
      this.id = row.id
      this.disableFormVisible = true
    },
    submitDisable(status) {
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.id)
      params.append('status', status)
      axios.post(process.env.BASE_API + '/app/approve', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
      this.disableFormVisible = false
    },
    handleViewAuth(row) {
      this.appStatus = row.status
      this.appName = row.name
      this.id = row.id
      this.getAppApi()
      this.showAppApis = true
    },
    getAppApi() {
      const vm = this
      axios.get(process.env.BASE_API + '/appapi/listbyappid', {
        params: {
          appId: vm.id
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.totalAuthDataNumber = 0
          vm.allAuthData = []
          vm.authData = []
        } else {
          vm.totalAuthDataNumber = parseInt(obj.total)
          if (vm.totalAuthDataNumber > 0) {
            vm.allAuthData = obj.data
            vm.authData = obj.data.slice(0, vm.pageAuthSize)
          } else {
            vm.allAuthData = []
            vm.authData = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    }
  }
}
</script>

<style scoped>
  .orderform {
    padding-top: 20px;
    padding-left: 10px;
    padding-right: 10px;
  }

  .mydiv {
    float: right;
    margin-right: 10px;
  }
</style>
