<template>
  <div class="apilist">
    <el-form
      ref="form"
      :model="form"
      :inline="true"
      class="orderform flex-between"
      size="mini"
    >
      <div>
        <el-form-item label="接口名称:" prop="tag">
          <el-input
            v-model="form.tag"
            style="width: 250px"
            placeholder="请输入..."
            class="search_tag"
            clearable
          />
        </el-form-item>
        <!-- <el-form-item prop="appId" label="应用列表">
          <el-select
            v-model="form.appId"
            placeholder="请选择"
            style="width: 250px"
            clearable
          >
            <el-option
              v-for="item in appList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            @click="allApis()"
          ><i class="el-icon-search" /> 搜索</el-button
          >
          <el-button
            @click="btn_clear()"
          ><i class="el-icon-remove-outline" /> 重置</el-button
          >
        </el-form-item>
        <el-form-item >
          <el-button
            type="primary"
            @click="addFormVisible = true"
          ><i class="el-icon-plus" /> 申请新增接口
          </el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="flex" style="background: #ffffff;height: 100%">
      <div class="text-center left">
        <div
          :class="{ active: !form.apiTypeId }"
          class="p-12 font-14 item"
          @click="handleApiList('')"
        >
          全部接口
        </div>
        <div
          v-for="(item, index) in apiList"
          :key="index"
          :class="{ active: form.apiTypeId === item.id }"
          class="p-10 font-14 item"
          @click="handleApiList(item.id)"
        >
          {{ item.name }}
        </div>
      </div>
      <div class="flex-1 w-95 right">
        <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="apis"
          :highlight-current-row="true"
          stripe
          fit
          height="calc(100% - 1px)"
          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="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 type="text" @click="handleDetail(scope.row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
          <el-table-column width="300" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="onClickDev(scope.row)">
                需求申请
              </el-button>
              <el-button
                v-if="scope.row.collect.isCollect === 1"
                disabled
                size="mini" type="text"
              >
                已收藏
              </el-button>
              <el-button
                v-else
                size="mini" type="text"
                @click="onclickcollectInsert(scope.row.id)"
              >
                收藏
              </el-button>
              <el-button v-if="scope.row.auth.accreditStatus === 1" size="mini" type="text">
                已授权
              </el-button>
              <el-button
                v-else-if="scope.row.auth.accreditStatus === 0"
                size="mini" type="text"
                @click="empowerClick(scope.row.id,scope.row.auth.id)"
              >
                申请授权
              </el-button>
              <el-button v-else size="mini" type="text">待审核</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--查看参数弹窗-->
    <el-dialog :visible.sync="paramsVisible" width="80%" title="参数查看">
      <el-table
        ref="multipleTable"
        :data="params"
        :highlight-current-row="true"
        stripe
        fit
        height="calc(100% - 1px)"
        border
      >
        <el-table-column prop="name" label="参数名称" />
        <el-table-column prop="type" label="参数类型" />
        <el-table-column prop="description" label="参数描述" />
        <el-table-column prop="required" label="是否必填" />
        <el-table-column prop="default" label="默认值" />
      </el-table>
    </el-dialog>
    <!--申请新增数据接口-->
    <el-dialog
      :visible.sync="addFormVisible"
      width="50%"
      title="申请新增数据接口"
    >
      <el-form ref="addForm" :model="addForm" label-width="120px">
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="addForm.mobile" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="需求描述" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            placeholder="请输入需求描述"
          />
        </el-form-item>
        <el-form-item label="接口名称" prop="apiName">
          <el-input v-model="addForm.apiName" placeholder="请输入接口名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addFormSubmit('addForm')"
        >确 定</el-button
        >
      </div>
    </el-dialog>
    <!--申请开发-->
    <el-dialog
      :visible.sync="applyForDevelopmentVisible"
      width="50%"
      title="申请开发"
    >
      <el-form ref="applyForDevelopmentForm" label-width="120px">
        <el-form-item label="联系手机号" prop="mobile">
          <el-input
            v-model="applyForDevelopmentForm.mobile"
            placeholder="请输入联系方式"
          />
        </el-form-item>
        <el-form-item label="申请字段" prop="fieldJson">
          <div
            v-for="(item, index) in applyForDevelopmentForm.fieldJson"
            :key="index"
            class="flex"
          >
            <el-input v-model="item.param" placeholder="请输入申请参数" />
            <el-input
              v-model="item.desc"
              class="ml-10"
              placeholder="请输入申请描述"
            />
            <el-button
              class="ml-10"
              type="danger"
              @click="removeField(index)"
            >删除</el-button
            >
          </div>
          <el-button
            type="primary"
            size="mini"
            class="mt-10"
            @click="addField"
          >添加</el-button
          >
        </el-form-item>
        <el-form-item label="需求描述" prop="description">
          <el-input
            v-model="applyForDevelopmentForm.description"
            type="textarea"
            placeholder="请输入需求描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="applyForDevelopmentVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="applyForDevelopment()"
        >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import {
  applyInsertApi,
  collectInsert,
  collectList,
  list,
  typeList
} from '@/api/apimngr'
import { apiNeedApplyInsert, appList } from '@/api/app'
import axios from 'axios'

export default {
  name: 'Apilist',
  data() {
    return {
      // 申请新增数据接口
      addFormVisible: false,
      addForm: {
        // 联系方式
        mobile: '',
        // 需求描述
        description: '',
        // 接口名称
        apiName: ''
      },
      // 申请开发
      applyForDevelopmentVisible: false,
      applyForDevelopmentForm: {
        // 接口id
        apiId: '',
        // 手机号
        mobile: '',
        // 需求描述
        description: '',
        fieldJson: [
          {
            param: '',
            desc: ''
          }
        ]
      },

      apiList: [],
      myapis: [],
      apis: [],
      activeNames: [],
      // right
      pageNo: 1,
      pageSize: 10,
      totalDataNumber: 0,
      // search
      form: {
        tag: ' ',
        apiTypeId: '',
        appId: null,
        roleId: null,
        accreditStatus: 1,
        status: 1
      },

      appList: [],
      // 参数弹窗
      paramsVisible: false,
      params: [],
      activeName: '1'
    }
  },
  created() {
    this.form.tag = this.$route.query.tag || ''
    this.form.roleId = this.user.roleId
  },
  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapState(['user'])
  },
  async mounted() {
    await this.applist()
    await this.searchAllApis()
    await this.allApis()
  },
  methods: {
    empowerClick(apiId, authId) {
      var params = new URLSearchParams()
      params.append('roleId', this.user.roleId)
      params.append('apiId', apiId)
      params.append('authId', authId)
      axios.post(process.env.BASE_API + '/role/applyForAuth', params).then(res => {
        if (res.data.code === 10000) {
          this.$message({
            message: '申请成功',
            type: 'success'
          })
          this.allApis()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    typeName(id) {
      const name = this.apiList.filter(val => val.id === id)[0].name
      return name
    },
    tabsClick() {
      this.form.accreditStatus = Number(this.activeName)
      this.allApis()
    },
    handleApiList(id) {
      this.form.apiTypeId = id
      this.allApis()
    },
    // 查看参数
    viewParams(item) {
      this.paramsVisible = true
      const params = JSON.parse(item.extJson)
      this.params = params ? params.params : []
    },
    // 跳转详情
    handleDetail(item) {
      this.$router.push({
        path: `/apilist/detail/${item.id}`,
        query: {
          state: item.auth.accreditStatus,
          aipId: item.apiType.id,
          authId: item.auth.id
        }
      })
    },
    async allApis() {
      // window.localStorage.setItem('appId', this.form.appId)
      const collectlist = await collectList()
      list(this.form).then(res => {
        if (res.data.length > 0) {
          this.apis = res.data.map(item => {
            item.collect = {}
            if (collectlist.data.find(v => v.apiId === item.id)) {
              item.collect = collectlist.data.find(v => v.apiId === item.id)
            }
            return item
          })
        } else {
          this.apis = []
          this.oldApis = []
        }
      })
    },
    btn_clear() {
      this.$refs['form'].resetFields()
      this.form.apiTypeId = ''
      this.allApis()
    },
    // 分类列表
    async searchAllApis() {
      const res = await typeList()
      this.apiList = res.data
    },
    // 应用列表
    async applist() {
      const res = await appList()
      this.appList = res.data
      // this.form.appId = this.appList[0].id
      // window.localStorage.setItem('appId', this.appList[0].id)
    },
    // 收藏
    async onclickcollectInsert(id) {
      const params = new URLSearchParams()
      params.append('apiId', id)
      await collectInsert(params)
      this.$message({
        message: '收藏成功',
        type: 'success'
      })
      this.allApis()
    },
    // 申请新增接口
    addFormSubmit() {
      // 校验手机号
      if (!/^1[3456789]\d{9}$/.test(this.addForm.mobile)) {
        this.$message.error('手机号码有误，请重填')
        return false
      }
      // 校验描述
      if (this.addForm.description === '') {
        this.$message.error('请填写描述')
        return false
      }
      // 校验接口名称
      if (this.addForm.apiName === '') {
        this.$message.error('请填写接口名称')
        return false
      }
      const params = new URLSearchParams()
      params.append('mobile', this.addForm.mobile)
      params.append('apiName', this.addForm.apiName)
      params.append('description', this.addForm.description)
      applyInsertApi(params).then(res => {
        this.addFormVisible = false
        if (res.data.code !== 10000) {
          this.$message.error(res.data.message)
          return
        }
        this.$message({
          message: '申请成功',
          type: 'success'
        })
      })
    },
    // 申请开发
    addField() {
      this.applyForDevelopmentForm.fieldJson.push({
        param: '',
        desc: ''
      })
    },
    removeField(index) {
      this.applyForDevelopmentForm.fieldJson.splice(index, 1)
    },
    onClickDev(data) {
      this.applyForDevelopmentVisible = true
      this.applyForDevelopmentForm.apiId = data.id
    },
    async applyForDevelopment() {
      // 校验手机号
      if (!/^1[3456789]\d{9}$/.test(this.applyForDevelopmentForm.mobile)) {
        this.$message({
          message: '请输入正确的手机号',
          type: 'error'
        })
        return
      }
      // 校验参数
      if (this.applyForDevelopmentForm.fieldJson.length === 0) {
        this.$message({
          message: '请添加参数',
          type: 'error'
        })
        return
      }
      for (const item of this.applyForDevelopmentForm.fieldJson) {
        if (item.param === '') {
          this.$message({
            message: '参数名称不能为空',
            type: 'error'
          })
          return
        }
        if (item.desc === '') {
          this.$message({
            message: '参数描述不能为空',
            type: 'error'
          })
          return
        }
      }
      // 校验描述
      if (this.applyForDevelopmentForm.description === '') {
        this.$message({
          message: '请填写描述',
          type: 'error'
        })
        return
      }
      const params = new URLSearchParams()
      params.append('apiId', this.applyForDevelopmentForm.apiId)
      params.append('mobile', this.applyForDevelopmentForm.mobile)
      params.append(
        'fieldJson',
        JSON.stringify(this.applyForDevelopmentForm.fieldJson)
      )
      params.append('description', this.applyForDevelopmentForm.description)
      await apiNeedApplyInsert(params)
      this.$message({
        message: '申请成功',
        type: 'success'
      })
      this.applyForDevelopmentVisible = false
    }
  }
}
</script>

<style scoped lang="scss">
.apilist {
  height: 92%;

  .orderform {
    margin-top: 20px;
  }

  .left {
    width: 150px;

    .item {
      margin: 10px;
      padding: 10px;
      border-bottom: 1px solid #dad6d6;
      border-style-width: 80%;
      //手势
      cursor: pointer;
      //动画
      transition: all 0.3s;

      &:hover {
        background: #409eff;
        color: #ffffff;
        border-radius: 5px;
        //动画
        transition: all 0.3s;
      }
    }

    //选中
    .active {
      background: #409eff;
      color: #ffffff;
      border-radius: 5px;
    }
  }

  .right {
    height: 100%;
  }

  .mydiv {
    display: flex;
    padding: 10px;
    background: #ffffff;
  }
}
</style>
