<template>
  <div>
    <div class="ml-10 flex-between">
      <div class="flex font-14">
        <div class="">
          <p>应用详情</p>
        </div>
        <div class="ml-10 mr-10">
          <p>到期日期:{{ appExpireDate }}</p>
        </div>
        <div>
          <p>应用描述:{{ appDescription }}</p>
        </div>
      </div>
      <el-button type="primary" @click="handleEdit()">编辑</el-button>
    </div>
    <div>
      <el-table
        :data="appData"
        :highlight-current-row="true"
        border>
        <el-table-column
          prop="name"
          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>
    <el-table
      :data="tableData"
      :highlight-current-row="true"
      height="calc(100vh - 360px)"
      border>
      <el-table-column
        prop="api.name"
        label="API"/>
      <el-table-column
        :formatter="formatStatus"
        prop="status"
        label="状态"/>
      <el-table-column
        prop="api.url"
        label="请求地址"/>
      <el-table-column
        prop="callLimit"
        label="调用限制量"/>
      <el-table-column
        prop="qpsLimit"
        label="QPS限制"/>
      <el-table-column
        label="更高QPS申请">
        <template slot-scope="scope">
          <div v-if="scope.row.qpsApply.id > 0">
            <span>--</span>
          </div>
          <div v-else>
            <el-button type="text" @click="applyQps(scope.row)"><span style="color: blue">立即申请</span></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="申请状态">
        <template slot-scope="scope">
          <div v-if="scope.row.qpsApply.applyStatus === 2">
            <span>审核中</span>
          </div>
          <div v-else-if="scope.row.qpsApply.applyStatus === 1">
            <span>更高配额 {{ scope.row.qpsApply.maxQps }} </span>
          </div>
          <div v-else-if="scope.row.qpsApply.applyStatus === 3">
            <span>审核拒绝 </span>
          </div>
          <div v-else>
            <span>默认配额</span>
          </div>

        </template>
      </el-table-column>
    </el-table>
    <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 m-10"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>
    <el-dialog :visible.sync="editFormVisible" title="编辑应用">
      <el-form :model="editForm" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="应用名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入应用名称"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="应用类型" prop="appType">
          <el-select v-model="editForm.appType" 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 :label-width="formLabelWidth" label="接口选择" prop="apis">
          <el-collapse
            v-for="book in apiList"
            v-model="activeNames"
            :key="book.name">
            <el-collapse-item :title="book.name" :name="book.name">
              <el-checkbox-group v-model="dataModel">
                <el-checkbox
                  v-for="api in book.apis"
                  :key="api.value"
                  :label="api.value"
                >{{ api.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="到期日期">
          <el-date-picker
            v-model="editForm.expireDate"
            :disabled="true"
            type="date"
            placeholder="选择到期日期"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="备注">
          <el-input
            v-model="editForm.description"
            type="textarea"
            show-word-limit
            maxlength="100"
            placeholder="请输入备注，最长100字"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnUpdateCancel">取 消</el-button>
        <el-button type="primary" @click="btnUpdateSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="applyQpsFormVisible" title="更高QPS申请">
      <el-form :model="qpsApplyForm" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="申请接口">
          <el-input v-model="qpsApplyForm.apiName" :disabled="true"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="应用名称">
          <el-input v-model="qpsApplyForm.appName" :disabled="true"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="应用类别">
          <el-input v-model="qpsApplyForm.appType" :disabled="true"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" :inline="true" label="预估最高QPS">
          <el-row>
            <el-col :span="16">
              <el-radio-group v-model="qpsApplyForm.maxQps" @change="radioChanged()">
                <el-radio :label="3">3</el-radio>
                <el-radio :label="5">5</el-radio>
                <el-radio :label="10">10</el-radio>
                <el-radio :label="250">其它</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="8">
              <el-input v-model="qpsApplyForm.otherQps" :disabled="qpsApplyForm.otherStatus" type="number"/>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="预估每日调用量" prop="callTimes">
          <el-input v-model="qpsApplyForm.callTimes" placeholder="请输入预估每日调用量" type="number"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" :inline="true" label="QPS计算公式">
          <el-row>
            <el-col :span="1">
              <el-tooltip :manual="false" placement="top">
                <div slot="content">
                  QPS（query per second）指每秒向服务器发送的请求数量峰值，<br>
                  相当于每个API接口每秒可以允许请求的并发上限量。<br>
                  计算公式：预计日调用量/预计处理时长（单位：秒）= 需求QPS<br>
                  请填入日调用量和每天处理小时数，计算您需要的QPS
                </div>
                <el-button size="mini" type="text">?</el-button>
              </el-tooltip>
            </el-col>
            <el-col :span="23">
              <el-form :inline="true">
                <el-form-item>
                  <span>日调用量</span>
                </el-form-item>
                <el-form-item>
                  <el-input v-model="calCallTime" size="mini" type="number" @change="calQpsFun()"/>
                </el-form-item>
                <el-form-item>
                  <span>每天处理</span>
                </el-form-item>
                <el-form-item>
                  <el-input v-model="calCallHour" size="mini" type="number" @change="calQpsFun()"/>
                </el-form-item>
                <el-form-item>
                  <span>小时 需求QPS量：{{ calQps }}</span>
                </el-form-item>
              </el-form>

            </el-col>
          </el-row>
        </el-form-item>
        <!--el-form-item :label-width="formLabelWidth" label="接入地域比例">
          <el-input v-model="qpsApplyForm.areas" placeholder="填写以;隔开,如： 北方 10%；南方 50%； 其它 40%"/>
        </el-form-item-->
        <el-form-item :label-width="formLabelWidth" label="公司名称" prop="companyName">
          <el-input v-model="qpsApplyForm.companyName" placeholder="请输入公司名称"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="联系电话" prop="phone">
          <el-input v-model="qpsApplyForm.phone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="联系邮箱" prop="email">
          <el-input v-model="qpsApplyForm.email" placeholder="请输入联系邮箱"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="应用介绍" prop="description">
          <el-input
            v-model="qpsApplyForm.description"
            :maxlength="1000"
            type="textarea"
            rows="5"
            placeholder="请描述使用场景，应用功能及特点，不超过1000字"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="提升配额原因" prop="applyReason">
          <el-input
            v-model="qpsApplyForm.applyReason"
            :maxlength="500"
            type="textarea"
            rows="3"
            placeholder="请描述具体原因，以便于顺利通过审批，不超过500字"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <p>您的审批将会在2个工作日内完成审批</p>
        <el-button type="primary" @click="applyQpsSubmit">提交申请</el-button>
        <el-button @click="applyQpsCancel">取 消</el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'Detail',
  data() {
    return {
      rules: {
        callTimes: [{ required: true, message: '请输入预估每日调用量', trigger: 'blur' }],
        companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        email: [{ required: true, message: '请输入联系邮箱', trigger: 'blur' }],
        description: [{ required: true, message: '请输入应用介绍', trigger: 'blur' }],
        applyReason: [{ required: true, message: '请输入提升配额原因', trigger: 'blur' }],
        name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
        appType: [{ required: true, message: '请选择应用类型', trigger: 'blur' }],
        apis: [{ required: true, message: '请选择应用所需接口', trigger: 'blur' }]
      },
      formLabelWidth: '150px',
      appTypes: [],
      apiList: [], // 所有接口列表
      dataModel: [], // 选中的接口列表
      activeNames: [],
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      appData: [], // app基本信息
      appId: '',
      appDescription: '',
      appExpireDate: '',
      editFormVisible: false,
      editForm: {
        id: '',
        name: '',
        appType: '',
        expireDate: '',
        description: ''
      },
      applyQpsFormVisible: false,
      qpsApplyForm: {
        appApiId: '',
        apiName: '',
        appName: '',
        appType: '',
        maxQps: 3,
        otherQps: '',
        otherStatus: true,
        callTimes: '',
        areas: '',
        companyName: '',
        phone: '',
        email: '',
        description: '',
        applyReason: ''
      },
      calQps: '',
      calCallTime: '',
      calCallHour: ''
    }
  },
  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.searchAllAppTypes()
    this.searchAllApis()
  },
  methods: {
    formatStatus(ob) {
      if (ob.status === 1) {
        return '正常'
      } else if (ob.status === 0) {
        return '异常/停用'
      } else if (ob.status === 2) {
        return '待审核'
      } else {
        return '未知'
      }
    },
    calQpsFun() {
      if (this.calCallTime !== 0 && this.calCallHour !== 0 && this.calCallHour !== '') {
        this.calQps = parseInt(this.calCallTime / (this.calCallHour * 3600))
      } else {
        this.calQps = ''
      }
      if (this.calQps === 0) {
        this.calQps = 1
      }
    },
    applyQpsSubmit() {
      if (this.qpsApplyForm.maxQps === '' || this.qpsApplyForm.maxQps === undefined) {
        this.$message.info('请输入预估最高QPS，不能为空')
        return
      }
      if (this.qpsApplyForm.callTimes === '' || this.qpsApplyForm.callTimes === undefined) {
        this.$message.info('请输入预估每日调用量，不能为空')
        return
      }
      if (this.qpsApplyForm.companyName === '' || this.qpsApplyForm.companyName === undefined) {
        this.$message.info('请输入公司名称，不能为空')
        return
      }
      if (this.qpsApplyForm.phone === '' || this.qpsApplyForm.phone === undefined) {
        this.$message.info('请输入联系电话，不能为空')
        return
      }
      if (this.qpsApplyForm.email === '' || this.qpsApplyForm.email === undefined) {
        this.$message.info('请输入联系邮箱\n，不能为空')
        return
      }
      if (this.qpsApplyForm.description === '' || this.qpsApplyForm.description === undefined) {
        this.$message.info('请输入应用介绍，不能为空')
        return
      }
      if (this.qpsApplyForm.applyReason === '' || this.qpsApplyForm.applyReason === undefined) {
        this.$message.info('请输入提升配额原因，不能为空')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('appApiId', vm.qpsApplyForm.appApiId)
      params.append('maxQps', vm.qpsApplyForm.otherQps || vm.qpsApplyForm.maxQps)
      params.append('callTimes', vm.qpsApplyForm.callTimes)
      params.append('areas', vm.qpsApplyForm.areas)
      params.append('companyName', vm.qpsApplyForm.companyName)
      params.append('phone', vm.qpsApplyForm.phone)
      params.append('email', vm.qpsApplyForm.email)
      params.append('description', vm.qpsApplyForm.description)
      params.append('applyReason', vm.qpsApplyForm.applyReason)
      axios.post(process.env.BASE_API + '/appapi/addapplyqps', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.getAppApi()
          vm.applyQpsFormVisible = false
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    applyQpsCancel() {
      console.log('')
    },
    radioChanged() {
      if (this.qpsApplyForm.maxQps !== 250) {
        this.qpsApplyForm.otherStatus = true
        this.qpsApplyForm.otherQps = ''
      } else {
        this.qpsApplyForm.otherStatus = false
      }
    },
    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 {
          if (parseInt(obj.total) > 0) {
            vm.appTypes = obj.data
          } else {
            vm.appTypes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    searchAllApis() {
      const vm = this
      axios.get(process.env.BASE_API + '/apimngr/listapis', {}).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apiList = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.apiList = obj.data
            vm.activeNames = obj.apiTypeNames
          } else {
            vm.apiList = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleEdit() {
      this.editForm.id = this.appData[0].id
      this.editForm.name = this.appData[0].name
      if (this.appData[0].appType !== null) {
        this.editForm.appType = this.appData[0].appType.id
      }
      this.editForm.expireDate = this.appData[0].expireDate
      if (this.appData[0].description === 'null') {
        this.editForm.description = ''
      } else {
        this.editForm.description = this.appData[0].description
      }
      this.editFormVisible = true
    },
    btnUpdateCancel() {
      this.editFormVisible = false
      this.editForm.name = ''
      this.editForm.expireDate = ''
      this.editForm.description = ''
    },
    btnUpdateSubmit() {
      if (this.editForm.name === '' || this.editForm.name === undefined) {
        this.$message.info('请输入应用类型名称，不能为空')
        return
      }
      if (this.editForm.appType === '' || this.editForm.appType === undefined) {
        this.$message.info('请选择应用类型，不能为空')
        return
      }
      if (this.dataModel.length === 0) {
        this.$message.info('请选择应用所需接口，不能为空')
        return
      }
      const vm = this
      const params = new URLSearchParams()
      params.append('id', vm.editForm.id)
      params.append('name', vm.editForm.name)
      params.append('appTypeId', vm.editForm.appType)
      params.append('apis', vm.dataModel)
      if (vm.editForm.expireDate === 'Invalid date') {
        vm.editForm.expireDate = ''
        params.append('expireDate', '')
      } else {
        params.append('expireDate', moment(vm.editForm.expireDate).format('YYYY-MM-DD'))
      }
      params.append('description', vm.editForm.description)
      axios.post(process.env.BASE_API + '/app/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.getAppDetail()
          vm.getAppApi()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    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() {
      const vm = this
      axios.get(process.env.BASE_API + '/appapi/listbyappid', {
        params: {
          appId: vm.appId
        }
      }).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)
      })
    },
    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)
    },
    getAppById(id) {
      const vm = this
      axios.get(process.env.BASE_API + '/app/findbyid', {
        params: {
          id: id
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.qpsApplyForm.appType = obj.data[0].appType.name
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    applyQps(data) {
      this.qpsApplyForm.appApiId = data.id
      this.qpsApplyForm.apiName = data.api.name
      this.qpsApplyForm.appName = data.app.name
      this.qpsApplyForm.companyName = this.appData[0].user.companyName
      this.qpsApplyForm.phone = this.appData[0].user.phone
      this.qpsApplyForm.email = this.appData[0].user.email
      this.qpsApplyForm.description = this.appData[0].description
      this.getAppById(data.app.id)
      this.applyQpsFormVisible = true
    }
  }
}
</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>
