<template>
  <el-dialog
    :title="$t(`${prefix}.response`)"
    :visible.sync="visibleProxy"
    width="700px"
    :close-on-click-modal="false"
    @close="onClose"
  >
    <div>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" plain size="mini" @click="copyParam">
            {{ $t(`${prefix}.copy_request_content`) }}
          </el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" plain size="mini" @click="copyResult">
            {{ $t(`${prefix}.copy_response_content`) }}
          </el-button>
        </el-col>
      </el-row>
      <el-divider content-position="left">
        {{ $t(`${prefix}.request_body`) }}
      </el-divider>
      <tree-view
        v-if="paramData"
        :data="paramData"
        :options="{ maxDepth: 2 }"
        style="line-height: 20px; text-align: left;"
      />
      <el-divider content-position="left">
        {{ $t(`${prefix}.response_content`) }}
      </el-divider>
      <tree-view
        v-if="resultData"
        :data="resultData"
        :options="{ maxDepth: 2 }"
        style="line-height: 20px; text-align: left;"
      />
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'ResponseDialog',
  props: {
    visible: { type: Boolean, default: false },
    paramData: { type: Object, default: null },
    resultData: { type: Object, default: null },
    prefix: { type: String, required: true }
  },
  computed: {
    visibleProxy: {
      get () { return this.visible },
      set (val) { this.$emit('update:visible', val) }
    }
  },
  methods: {
    onClose () {
      this.$emit('update:visible', false)
    },
    copyToClipboard (data) {
      const input = document.createElement('input')
      input.value = JSON.stringify(data)
      document.body.appendChild(input)
      input.select()
      document.execCommand('Copy')
      input.style.display = 'none'
      this.$message.success(this.$t(`${this.prefix}.operation_success`))
    },
    copyParam () {
      this.copyToClipboard(this.paramData)
    },
    copyResult () {
      this.copyToClipboard(this.resultData)
    }
  }
}
</script>
