<template>
  <div>
    <div class="ml-10 flex-between">
      <div class="flex font-14">
        <div class="">
          <p>应用详情:{{ appDescription }}</p>
        </div>
      </div>
      <!-- <el-button type="primary" @click="btnUpdateSubmit">更新</el-button> -->
    </div>
    <div>
      <el-table :data="appData" :highlight-current-row="true" border>
        <el-table-column prop="name" label="应用名称"/>
        <el-table-column label="应用类型">
          <template slot-scope="scope">
            <span>{{ scope.row.appType.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="应用备注"/>
        <el-table-column prop="id" label="AppID" />
        <el-table-column prop="apiKey" label="API Key" />
        <el-table-column prop="secretKey" label="Secret Key" />
      </el-table>
    </div>
    <p class="ml-10">API列表:</p>
    <div style="padding: 0 15px;">
      <el-form
        :model="form"
        :inline="true"
        size="mini">
        <el-form-item label="接口名称:" >
          <el-input
            v-model="form.tag"
            style="width: 250px"
            placeholder="请输入..."
            class="search_tag"
            clearable
          />
        </el-form-item>
        <el-form-item label="接口类型:" >
          <el-select v-model="form.apiTypeId" clearable placeholder="请选择应用类型">
            <el-option
              v-for="item in apiList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="getAppApi">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" @tab-click="tabsClick">
        <el-tab-pane name="1" label="已授权" />
        <el-tab-pane name="0" label="未授权" />
        <el-tab-pane name="2" label="待审核授权" />
      </el-tabs>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :highlight-current-row="true"
        height="calc(100vh - 420px)"
        border
      >
        <el-table-column prop="name" label="接口名称" />
        <el-table-column label="接口类型">
          <template slot-scope="scope">
            <span>{{ typeName(scope.row.apiType.id) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="authState" label="使用状态">
          <template slot-scope="scope">
            <el-button v-if="scope.row.authState === 0" disabled plain type="warning">
              待审核
            </el-button>
            <el-button v-else-if="scope.row.authState === 1" disabled plain type="success">
              正常使用
            </el-button>
            <el-button v-else disabled plain type="info">
              未申请
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="启停状态" >
          <template slot-scope="scope">
            <span v-if="scope.row.enable === 0">启用</span>
            <span v-if="scope.row.enable === 1">停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="请求地址" />
        <!-- <el-table-column prop="callLimit" label="调用量限制" /> -->
        <el-table-column prop="qpsLimit" label="QPS限制" />
        <el-table-column width="100" prop="description" label="查看详情">
          <template slot-scope="scope">
            <el-button :disabled="scope.row.enable === 1" type="text" @click="handleDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table
    ></div>

  </div>
</template>

<script>
import axios from 'axios'
import {
  list,
  typeList
} from '@/api/apimngr'
export default {
  name: 'Detail',
  data() {
    return {

      appTypes: [],
      apiList: [], // 所有接口列表
      dataModel: [], // 选中的接口列表
      activeNames: [],
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      appData: [], // app基本信息
      appId: '',
      appDescription: '',
      appExpireDate: '',
      editFormVisible: false,
      activeName: '1',
      form: {
        appId: null,
        accreditStatus: 1,
        status: 1,
        roleId: null,
        apiTypeId: null
      },
      useApis: [],
      authState: []
    }
  },
  created() {
    // 取到路由带过来的参数
    this.appId = this.$route.query.appId
    if (this.appId === null && this.appId === undefined && this.appId === '') {
      this.$message.error('无法获取应用信息')
      return
    } else {
      this.getAppDetail()
      this.getAppApi()
    }
    this.searchAllApis()
    this.searchAllAppTypes()
  },
  methods: {
    typeName(id) {
      const name = this.apiList.filter(val => val.id === id)[0].name
      return name
    },
    // 分类列表
    async searchAllApis() {
      const res = await typeList()
      this.apiList = res.data
    },
    // 应用申请使用接口
    applyApi(item) {
      this.$confirm('申请使用该接口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = new URLSearchParams()
        params.append('appId', this.appId)
        params.append('apiId', item.id)
        params.append('callLimit', item.callLimit)
        params.append('qpsLimit', item.qpsLimit)
        axios.post(process.env.BASE_API + '/appapi/addAppApi', params).then(res => {
          if (res.code === 10000) {
            this.$message.success('接口已申请!')
            this.getAppApi()
          }
        })
      })
    },
    formatStatus(ob) {
      // if (ob.authState === 1) {
      //   return '正常'
      // } else if (ob.authState === 0) {
      //   return '异常/停用' // 待
      // } else if (ob.authState === 2) {
      //   return '待审核'
      // } else {
      //   return '未知'
      // }
      if (ob.authState === 0) {
        return '待审核'
      } else if (ob.authState === 1) {
        return '正常使用'
      } else {
        return '可申请'
      }
    },
    // 跳转详情
    handleDetail(item) {
      this.$router.push({
        path: `/apilist/detail/${item.id}`,
        query: {
          state: item.auth.accreditStatus,
          aipId: item.apiType.id,
          authId: item.auth.id,
          appId: this.appId
        }
      })
    },
    handleSelectionChange(e) {
      // console.log(e)
    },
    // 获取已应用接口
    getUseApi() {
      axios.get(process.env.BASE_API + '/appapi/getCheckApiList', {
        params: {
          appId: this.appId
        }
      }).then(res => {
        const data = res.data
        if (data.code === 10000) {
          this.useApis = data.data
          const arr = this.tableData.filter(val => data.data.includes(val.id))
          // console.log(arr)
          arr.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        }
      })
    },
    tabsClick() {
      this.form.accreditStatus = Number(this.activeName)
      this.getAppApi()
    },
    // 查询所有引用分类
    searchAllAppTypes() {
      const vm = this
      axios
        .get(process.env.BASE_API + '/apptype/list', {})
        .then(function(response) {
          const obj = response.data
          if (obj.code !== 10000) {
            vm.$message.error(obj.message)
            vm.appTypes = []
          } else {
            if (parseInt(obj.total) > 0) {
              vm.appTypes = obj.data
            } else {
              vm.appTypes = []
            }
          }
        })
        .catch(function(error) {
          alert(error)
        })
    },

    // 编辑
    btnUpdateSubmit() {
      if (this.appData[0].name === '') {
        this.$message.info('请输入应用类型名称，不能为空')
        return
      }
      if (this.appData[0].appType.id === '') {
        this.$message.info('请选择应用类型，不能为空')
        return
      }
      this.$confirm('确定要更新吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = new URLSearchParams()
        params.append('id', this.appData[0].id)
        params.append('name', this.appData[0].name)
        params.append('appTypeId', this.appData[0].appType.id)
        params.append('description', this.appData[0].description)
        params.append('expireDate', '')
        axios.post(process.env.BASE_API + '/app/update', params)
          .then(function(response) {
            const obj = response.data
            if (obj.code !== 10000) {
              this.$message.error(obj.message)
            } else {
              this.$message(obj.message)
              this.getAppDetail()
            }
          })
      })
    },
    getAppDetail() {
      // console.log(this.appId)
      const vm = this
      axios
        .get(process.env.BASE_API + '/app/findbyid', {
          params: {
            id: parseInt(vm.appId)
          }
        })
        .then(function(response) {
          var obj = response.data
          if (obj.code !== 10000) {
            vm.$message.error(obj.message)
            vm.appData = []
          } else {
            vm.appData = obj.data
            vm.dataModel = obj.dataModel
            vm.appDescription = vm.appData[0].description
            vm.appExpireDate = vm.appData[0].expireDate
          }
        })
        .catch(function(error) {
          alert(error)
        })
    },
    getAppApi() {
      axios.get(process.env.BASE_API + '/appapi/listbyappid', {
        params: {
          appId: this.appId
        }
      }).then(res => {
        const data = res.data
        if (data.data && data.data.length > 0) {
          this.authState = data.data.map(val => { return { id: val.api.id, state: val.status, enable: val.enable } })
        }
        list(this.form).then(res => {
          if (res.code === 10000) {
            if (res.data.length > 0) {
              this.tableData = res.data
              this.tableData.map(val => {
                const obj = this.authState.find(item => item.id === val.id)
                if (obj) {
                  val.authState = obj.state
                  val.enable = obj.enable
                } else {
                  val.authState = 2
                  val.enable = 0
                }
                return val
              })
            } else {
              this.tableData = []
            }
            // this.getUseApi()
          }
        })
      })
    }
  }
}
</script>

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

.mt {
  margin-top: 10px;
}

.line {
  margin-top: 20px;
  width: 100%;
  border-bottom: 3px solid #f2f2f2;
}
</style>
