<template>
  <div class="AppListDetail">
    <div class="left">
      <!-- <div class="fr">
        <el-button>申请开发</el-button>
        <el-button v-if="!collect" @click="onclickcollectInsert">收藏</el-button>
        <el-button v-else type="success">已收藏</el-button>
        <el-button v-if="!isApply" @click="submitApp">权限申请</el-button>
        <el-button v-else type="success">已申请</el-button>
      </div> -->
      <div class="clearfix"/>
      <el-divider/>
      <el-row :gutter="20" class="mt-10">
        <el-col :span="8">
          <div>
            <el-statistic :precision="0" :value="detail.apiBrowserNum" group-separator="," title="浏览次数"/>
          </div>
        </el-col>
        <el-col :span="8">
          <div>
            <el-statistic :precision="0" :value="detail.apiInvokeNum" group-separator="," title="使用次数"/>
          </div>
        </el-col>
        <el-col :span="8">
          <div>
            <el-statistic :precision="0" :value="detail.apiCollectNum" group-separator="," title="收藏次数"/>
          </div>
        </el-col>
      </el-row>
      <el-divider/>
      <div class="title">
        接口名称：{{ detail.api.name }}
      </div>
      <el-divider/>
      <div class="title">
        负责人：{{ detail.api.createBy }}
      </div>
      <el-divider/>
      <div class="title">
        创建时间：{{ detail.api.createTime }}
      </div>
      <el-divider/>
      <div class="title">
        更新时间：{{ detail.api.updateTime }}
      </div>
      <el-divider/>
      <div class="title">
        api版本：{{ detail.api.version }}
      </div>
      <el-divider/>
      <div class="title">
        api说明：{{ detail.api.description }}
      </div>
      <el-divider/>
      <div class="title">
        黑名单：{{ detail.api.blackList }}
      </div>
      <el-divider/>
      <div class="title">
        白名单：{{ detail.api.whiteList }}
      </div>
    </div>
    <el-divider class="h-100" direction="vertical"/>
    <div class="right">
      <el-tabs v-model="activeName">
        <el-tab-pane label="参数信息" name="a1">
          <el-divider v-if="isHeaderShow" class="dividerTitle" content-position="left">请求headers</el-divider>
          <el-table
            v-if="isHeaderShow"
            :data="detail.api.extJson.headers"
            :header-cell-style="{
              'background-color': '#f5f6fa'
            }"
            stripe
            style="width: 100%">
            <el-table-column label="参数名称" prop="name"/>
            <el-table-column label="是否必填" prop="required"/>
            <el-table-column label="参数说明" prop="description"/>
            <el-table-column label="参数值" prop="default"/>
          </el-table>
          <el-divider class="dividerTitle" content-position="left">请求参数</el-divider>
          <el-table
            :data="detail.api.extJson.params"
            :header-cell-style="{
              'background-color': '#f5f6fa'
            }"
            stripe
            style="width: 100%">
            <el-table-column label="参数名称" prop="name" width="300"/>
            <el-table-column label="参数类型" prop="type" width="300"/>
            <el-table-column label="是否必填" prop="required" width="300"/>
            <el-table-column label="参数说明" prop="description"/>
            <el-table-column label="默认值" prop="default"/>
          </el-table>
          <div class="mt-30">
            <el-divider content-position="left">返回参数</el-divider>
          </div>
          <el-table
            :data="detail.api.extJson.returnParams"
            :header-cell-style="{
              'background-color': '#f5f6fa'
            }"
            :tree-props="{children: 'children'}"
            fit
            stripe
            row-key="name"
            default-expand-all
            style="width: 100%">
            <el-table-column label="参数名称" prop="name" />
            <el-table-column label="参数类型" prop="type" width="300"/>
            <el-table-column label="参数说明" prop="description"/>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="血缘关系" name="a2">
          <tree v-if="kinship" :series="kinship" height="77vh" width="80vh"/>
        </el-tab-pane>
        <el-tab-pane label="使用说明" name="a3">
          <div class="title">
            <div class="flex title">
              <div class="mr-30">
                前置鉴权接口：{{ domain }}/oauth/2.0/token
                <el-button size="mini" type="text" @click="handleCopy(domain + '/oauth/2.0/token', $event)">复制
                </el-button>
                <el-popover placement="bottom-start" trigger="click" width="600">
                  <div>
                    <div class="mr-10">说明：</div>
                    <div>前置鉴权接口，获取access_token</div>
                    <div>请求方式：POST</div>
                    <div>请求参数：</div>
                    <pre>
{
	"client_id": "{{ appDetail.apiKey }}",
	"client_secret": "{{ appDetail.secretKey }}",
	"grant_type": "access_token"
}
                    </pre>
                    <div>响应示例</div>
                    <pre>
{
	"access_token": "40698380fac4e6560d8023a9b46f32a1",
	"expires_in": 1694351955
}
                    </pre>
                  </div>
                  <el-button slot="reference" size="mini" type="text">说明</el-button>
                </el-popover>
              </div>
              <template v-if="appId!=null">
                <div class="mr-30">
                  apiKey：{{ appDetail.apiKey }}
                  <el-button size="mini" type="text" @click="handleCopy(appDetail.apiKey, $event)">复制</el-button>
                </div>
                <div class="">
                  apiSecret：{{ appDetail.secretKey }}
                  <el-button size="mini" type="text" @click="handleCopy(appDetail.secretKey, $event)">复制</el-button>
                </div>
              </template>

            </div>
          </div>
          <div class="title">
            接口地址：{{ detail.api.cgiUrl }}
            <el-button size="mini" type="text" @click="handleCopy(detail.api.cgiUrl, $event)">复制</el-button>
          </div>
          <el-divider/>
          <div class="title">
            请求方式：{{ detail.api.extJson.method }} <span style="width: 140px"/>  请求类型：{{ detail.api.extJson.type == 'add' ? '入库接口' : '查询接口' }}
          </div>
          <div class="title">
            <el-divider content-position="left">header请求参数</el-divider>
            <el-table
              :data="headerData"
              :header-cell-style="{
                'background-color': '#f5f6fa'
              }"
              stripe
              style="width: 100%">
              <el-table-column label="参数名称" prop="name" width="300"/>
              <!-- <el-table-column label="参数类型" prop="type" width="300"/> -->
              <el-table-column label="是否必填" prop="required" width="300"/>
              <el-table-column label="参数说明" prop="description"/>
              <el-table-column label="默认值" prop="default"/>
            </el-table>
          </div>
          <div class="title">
            <el-divider content-position="left">请求参数</el-divider>
            <el-table
              :data="detail.api.extJson.params"
              :header-cell-style="{
                'background-color': '#f5f6fa'
              }"
              stripe
              style="width: 100%">
              <el-table-column label="参数名称" prop="name" width="300"/>
              <el-table-column label="参数类型" prop="type" width="300"/>
              <el-table-column label="是否必填" prop="required" width="300"/>
              <el-table-column label="参数说明" prop="description"/>
              <el-table-column label="默认值" prop="default"/>
            </el-table>
          </div>
          <div class="title">
            <el-divider content-position="left">返回参数</el-divider>
            <el-table
              :data="detail.api.extJson.returnParams"
              :header-cell-style="{
                'background-color': '#f5f6fa'
              }"
              :tree-props="{children: 'children'}"
              fit
              stripe
              row-key="name"
              default-expand-all
              style="width: 100%">
              <el-table-column label="参数名称" prop="name" width="300"/>
              <el-table-column label="参数类型" prop="type" width="300"/>
              <el-table-column label="参数说明" prop="description" width="300"/>
            </el-table>
          </div>
          <el-divider/>
          <div class="title">
            <el-divider content-position="left">返回示例</el-divider>
            <pre>{{ detail.api.extJson.response }}
            </pre>
          </div>
        </el-tab-pane>
        <el-tab-pane label="历史版本" name="a4">
          <el-table
            :data="versionList"
            :header-cell-style="{
              'background-color': '#f5f6fa'
            }"
            stripe
            style="width: 100%">
            <el-table-column label="修改人" prop="createBy"/>
            <el-table-column label="修改时间" prop="createTime"/>
            <el-table-column label="历史版本号" prop="oldVersion"/>
            <el-table-column label="修改内容" prop="remark"/>
          </el-table>
        </el-tab-pane>
        <!-- <el-tab-pane label="意见反馈" name="a5">
          <el-form ref="applyForDevelopmentForm" :model="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="item.param" 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 class="mt-10" size="mini" type="primary" @click="addField">添加</el-button>
            </el-form-item>
            <el-form-item label="需求描述" prop="description">
              <el-input v-model="applyForDevelopmentForm.description" placeholder="请输入需求描述" type="textarea"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="applyForDevelopment">提交</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane> -->
      </el-tabs>
    </div>
  </div>
</template>

<script>
import tree from '@/components/Charts/tree.vue'
import { collectInsert, collectList, findbyid, findRelationbyid, versionList } from '@/api/apimngr'
import clip from '@/utils/clipboard'
import axios from 'axios'
import { apiNeedApplyInsert } from '@/api/app' // use clipboard directly
export default {
  name: 'Applistdetail',
  components: { tree },
  data() {
    return {
      // 当前域名
      domain: 'https://windata.platomix.net/api-cgi/cgi',
      id: 0,
      activeName: 'a1',
      headerData: [
        {
          name: 'access_token',
          type: 'string',
          required: '是',
          description: '请使用鉴权接口获取',
          default: ''
        }
      ],
      // 反馈内容
      applyForDevelopmentForm: {
        // 接口id
        apiId: '',
        // 手机号
        mobile: '',
        // 需求描述
        description: '',
        fieldJson: [
          {
            param: '',
            desc: ''
          }
        ]
      },
      // 详情
      detail: {
        api: {
          extJson: {
            params: [],
            returnParams: [],
            response: ''
          }
        }
      },
      kinship: '',
      versionList: [],
      // 应用详情
      appDetail: {},
      // 是否申请
      isApply: false,
      // 收藏列表
      collect: {
        acId: ''
      },
      state: '', // 接口状态,
      apiId: null,
      authId: null,
      appId: null,
      isHeaderShow: false
    }
  },
  async created() {
    this.id = this.$route.params.id * 1
    this.state = this.$route.query.state
    this.apiId = this.$route.query.apiId
    this.authId = this.$route.query.authId
    if (this.$route.query.appId) {
      this.appId = this.$route.query.appId
    } else {
      this.appId = null
    }

    // this.init()
    findbyid(this.id).then(res => {
      const extJson = res.data.api.extJson
      res.data.api.extJson = { ...this.detail.api.extJson, ...JSON.parse(extJson) }
      this.detail = res.data
      // 设置网页标题
      // document.title = this.detail.api.name
      this.init()
      // findRelationbyid(this.id).then(res => {
      //   // eslint-disable-next-line no-undef
      //   const nest = yang.nest()
      //     .key(function(d) {
      //       return d.appType ? d.appType.name : '未知'
      //     })
      //     .key(function(d) {
      //       return d.name
      //     })
      //     .rollup(function(leaves) {
      //       return leaves.length
      //     })
      //     .entries(res.data.applist)
      //   this.kinship = {
      //     name: this.detail.api.name,
      //     children: nest
      //   }
      // })
    })
    versionList(this.id).then(res => {
      this.versionList = res.data
    })

    this.getDetail()
  },
  methods: {
    getDetail() {
      findbyid(this.id).then(res => {
        const extJson = res.data.api.extJson
        res.data.api.extJson = { ...this.detail.api.extJson, ...JSON.parse(extJson) }
        if (res.data.api.extJson.headers) {
          this.headerData = this.headerData.concat(res.data.api.extJson.headers)
          this.isHeaderShow = true
        }
        this.detail = res.data
        findRelationbyid(this.id).then(res => {
        // eslint-disable-next-line no-undef
          const nest = yang.nest()
            .key(function(d) {
              return d.appType ? d.appType.name : '未知'
            })
            .key(function(d) {
              return d.name
            })
            .rollup(function(leaves) {
              return leaves.length
            })
            .entries(res.data.applist)
          this.kinship = {
            name: this.detail.api.name,
            children: nest
          }
        })
      })
    },
    async init() {
      if (this.appId !== null) {
        const appDetail = await axios.get(process.env.BASE_API + '/app/findbyid', {
          params: {
            id: parseInt(this.appId)
          }
        })
        this.appDetail = appDetail.data.data[0]
        // this.isApply = appDetail.data.dataModel.includes(this.id)
      }

      const collectlist = await collectList()
      this.collect = collectlist.data.find(v => v.apiId === this.id)
    },
    handleCopy(text, event) {
      clip(text, event)
    },
    // 收藏
    async onclickcollectInsert() {
      const params = new URLSearchParams()
      params.append('apiId', this.id)
      await collectInsert(params)
      this.init()
      this.$message({
        message: '收藏成功',
        type: 'success'
      })
    },
    // 权限申请
    submitApp() {
      axios.get(process.env.BASE_API + '/app/findbyid', {
        params: {
          id: parseInt(this.appId)
        }
      }).then(res => {
        const vm = this
        if (res.data.code !== 10000) {
          this.$message.error(res.data.message)
          return
        }
        const editForm = res.data.data[0]
        const params = new URLSearchParams()
        params.append('id', editForm.id)
        params.append('name', editForm.name)
        params.append('appTypeId', editForm.appType.id)
        params.append('apis', [...res.data.dataModel, ...[this.id]].toString())
        params.append('description', editForm.description)
        params.append('expireDate', editForm.expireDate)
        axios.post(process.env.BASE_API + '/app/update', params).then(response => {
          const obj = response.data
          if (obj.code !== 10000) {
            vm.$message.error(obj.message)
          } else {
            this.init()
            vm.$message(obj.message)
          }
        }).catch(function(error) {
          alert(error)
        })
      })
    },
    // 申请开发
    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.id)
      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 lang="scss" scoped>
.AppListDetail {
  display: flex;
  justify-content: space-between;
  background: #ffffff;
  height: 100%;

  .left {
    width: 300px;
    padding: 15px;

    .title {
      font-size: 14px;
      margin-bottom: 10px;
      margin-top: 20px;
      color: #606266;
    }

    .el-divider--horizontal {
      margin: 10px 0;
    }
  }

  .right {
    flex: 1;
    padding: 0 5px;
    height: 86vh;
    overflow: auto;

    /deep/ .el-tabs__header {
      position: sticky;
      top: 0;
      background: #ffffff;
      z-index: 9;
    }

    .title {
      font-size: 14px;
      margin-bottom: 10px;
      margin-top: 20px;
      color: #606266;
    }

    pre {
      background: #f5f7fa;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 10px;
      margin-top: 20px;
      font-size: 12px;
      line-height: 1.5;
      color: #606266;
      word-wrap: break-word;
      white-space: pre-wrap;
      word-break: break-all;
    }

    .el-divider--horizontal {
      margin: 30px 0;

      .el-divider__text {
        font-size: 17px;
        font-weight: bold;
      }
    }
  }
}
</style>
