<template>
  <div>
    <el-card class="box-card" shadow="always">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
        <el-button-group style="float: right;">
          <el-button size="mini" icon="el-icon-s-data" round @click="apiDataCall">api调用</el-button>
          <el-button size="mini" icon="el-icon-back" round @click="showCard">返回</el-button>
        </el-button-group>
      </div>
      <div :style="classCardbody">
        <el-row>
          <el-col :span="8">API名称：{{form.apiName}}</el-col>
          <el-col :span="8">API版本：{{form.apiVersion}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="8">API路径：{{form.apiUrl}}</el-col>
          <el-col :span="8">请求类型：{{form.reqMethod}}</el-col>
          <el-col :span="8">返回格式：{{form.resType}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-tabs type="border-card" v-model="activeTabName">
              <el-tab-pane label="请求头" name="table0">
                <el-table :data="apiHeaderList" stripe border
                          :max-height="300"
                          style="width: 100%; margin: 15px 0;">
                  <el-table-column label="序号" width="55" align="center">
                    <template slot-scope="scope">
                      <span>{{ scope.$index +1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="authorization" label="Authorization" align="center" show-overflow-tooltip >
                  </el-table-column>
                  <el-table-column prop="apiKey" label="api_key" align="center" show-overflow-tooltip >
                  </el-table-column>
                  <el-table-column prop="secretKey" label="secret_key" align="center" show-overflow-tooltip >
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="请求参数" name="table1">
                <el-form ref="form" :rules="rules" :model="form">
                  <el-table :data="form.reqParams" stripe border
                            :max-height="300"
                            style="width: 100%; margin: 15px 0;">
                    <el-table-column label="序号" width="55" align="center">
                      <template slot-scope="scope">
                        <span>{{ scope.$index +1 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="paramName" label="参数名称" align="center" show-overflow-tooltip >
                    </el-table-column>
                    <el-table-column prop="nullable" label="是否允许为空" align="center" show-overflow-tooltip >
                      <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.nullable" true-label="1" false-label="0"></el-checkbox>
                      </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="描述" align="center" show-overflow-tooltip >
                    </el-table-column>
                    <el-table-column prop="paramType" label="参数类型" align="center" show-overflow-tooltip >
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.paramType" placeholder="请选择参数类型">
                          <el-option
                            v-for="dict in paramTypeOptions"
                            :key="dict.id"
                            :label="dict.itemValue"
                            :value="dict.itemText"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="whereType" label="操作符" align="center" show-overflow-tooltip >
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.whereType" placeholder="请选择操作符">
                          <el-option
                            v-for="dict in whereTypeOptions"
                            :key="dict.id"
                            :label="dict.itemValue"
                            :value="dict.itemText"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="paramValue" label="参数值" align="center" show-overflow-tooltip >
                      <template slot-scope="scope">
                        <el-form-item :prop=" 'reqParams.' + scope.$index + '.paramValue' " :rules="rules.paramValue">
                          <el-input v-model="scope.row.paramValue" placeholder="请输入参数值" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
        <el-divider content-position="left">返回数据</el-divider>
        <el-row>
          <el-col :span="24">
            <el-table :data="callData.dataList" stripe border
                      :max-height="200"
                      style="width: 100%; margin: 15px 0;">
              <el-table-column label="序号" width="55" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <template v-for="(column, index) in callData.columnList">
                <el-table-column
                  :prop="column"
                  :label="column"
                  :key="index"
                  align="center"
                  show-overflow-tooltip
                />
              </template>
            </el-table>
            <el-pagination
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="callData.pageNum"
              :page-size.sync="callData.pageSize"
              :total="callData.dataTotal"
            ></el-pagination>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getDataApi } from '@/api/market/dataapi'
import { getApiHeader, getApiCall, postApiCall } from '@/api/market/apicall'
import storage from '@/utils/storage'

export default {
  name: 'DataApiCall',
  props: {
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      classCardbody: {
        overflow: 'auto',
        height: document.body.offsetHeight - 240 + 'px'
      },
      title: '数据API调用',
      // 展示切换
      showOptions: {
        data: {},
        showList: true,
        showAdd: false,
        showEdit: false,
        showDetail: false,
        showCall: false
      },
      activeTabName: 'table0',
      form: {},
      rules: {
        paramValue: [{ required: true, message: "参数值不能为空", trigger: "blur" }]
      },
      apiHeader: {},
      apiHeaderList: [],
      // 操作符数据字典
      whereTypeOptions: [],
      // 参数类型数据字典
      paramTypeOptions: [],
      callData: {
        dataList: [],
        columnList: [],
        pageNum: 1,
        pageSize: 20,
        dataTotal: 0
      }
    }
  },
  created () {
    console.log('id:' + this.data.id)
    this.getDicts('data_where_type').then(response => {
      if (response.success) {
        this.whereTypeOptions = response.data
      }
    })
    this.getDicts('data_param_type').then(response => {
      if (response.success) {
        this.paramTypeOptions = response.data
      }
    })
    this.getDataApi(this.data.id)
    this.getApiHeader(this.data.id)
  },
  methods: {
    showCard () {
      this.$emit('showCard', this.showOptions)
    },
    /** 获取详情 */
    getDataApi: function (id) {
      getDataApi(id).then(response => {
        if (response.success) {
          this.form = response.data
        }
      })
    },
    getApiHeader: function (id) {
      getApiHeader(id).then(response => {
        if (response.success) {
          let data = response.data
          this.apiHeader = data
          let token = storage.ss.get('vue_template_token')
          data.authorization = 'Bearer ' + token
          this.apiHeaderList.push(data)
        }
      })
    },
    handleSizeChange (val) {
      this.callData.pageNum = 1
      this.callData.pageSize = val
      this.apiDataCall()
    },
    handleCurrentChange (val) {
      this.callData.pageNum = val
      this.apiDataCall()
    },
    apiDataCall () {
      this.$refs.form.validate(valid => {
        if (valid) {
          let url = this.form.apiUrl
          let header = {api_key: this.apiHeader.apiKey, secret_key: this.apiHeader.secretKey}
          let data = {}
          data.pageNum = this.callData.pageNum
          data.pageSize = this.callData.pageSize
          this.form.reqParams.forEach(param => {
            this.$set(data, param.paramName, param.paramValue)
          })
          if (this.form.reqMethod === 'GET') {
            getApiCall(url, header, data).then(response => {
              if (response.success) {
                const { data } = response
                let dataList = data.data || []
                let columnList = []
                if (dataList.length > 0) {
                  columnList = Object.keys(dataList[0])
                }
                this.callData.dataList = dataList
                this.callData.columnList = columnList
                this.callData.dataTotal = data.total
              }
            })
          } else if (this.form.reqMethod === 'POST') {
            postApiCall(url, header, data).then(response => {
              if (response.success) {
                const { data } = response
                let dataList = data.data || []
                let columnList = []
                if (dataList.length > 0) {
                  columnList = Object.keys(dataList[0])
                }
                this.callData.dataList = dataList
                this.callData.columnList = columnList
                this.callData.dataTotal = data.total
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
