<template>
  <!-- 组件功能：查看json及复制 -->
  <div class="showCopyJsonPop">

    <!-- 点开查看Json转换后table弹窗 -->
    <el-dialog 
      top="50px"
      :visible.sync="JsonTableShow"
      :modal-append-to-body="true"
      :append-to-body="true"
      :show-close="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      width="90%"
      @close="closePop"
    >
      <template #title>
        内容详情
        <el-button 
          size="mini"
          @click="copyJsonHandle()" 
          type="primary" 
          style="margin-right: 30px;float: right;"
        >复制JSON</el-button>
      </template>
      <el-table
        height="calc(100vh - 220px)"
        :data="JsonTableData"
        :border="true"
        style="width: 100%">
        <el-table-column
          prop="name"
          width="220"
          label="属性"
        >
          <template slot-scope="scope">
            {{ scope.row.name }}
            <el-button 
              type="primary"
              v-if="(scope.row.name).toUpperCase() == 'DETAILS'"
              size="mini"
              style="margin-left: 20px;"
              @click="showDetailTableHandle(scope.row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="值"
        >
          <template slot-scope="scope">
              <!-- DETAILS todo:DETAILS判断条件需要优化，使用传参的方式 -->
              <span v-if="(scope.row.name).toUpperCase() != 'DETAILS'">{{scope.row.value}}</span>
              <el-table
                v-else
                :data="scope.row.value"
                stripe
                :border="true"
                style="width: 100%"
                height="300"
              >
                <el-table-column
                  label="序号"
                  fixed="left"
                  type="index"
                  width="50">
                </el-table-column>
                <el-table-column
                  v-for="(head,h_key) in detailTableHeader"
                  :key="h_key"
                  min-width="120"
                >
                  <template #header>
                    <span :title="head">{{ head }}</span>
                  </template>
                  <template slot-scope="scope2">
                    <div v-if="typeof scope2.row[head] == 'object'">
                      <div v-for="(o,o_key) in scope2.row[head]">
                        {{ o_key }}：{{ o }}
                        <div style="border-bottom: dashed 1px #ddd;"></div>
                      </div>
                    </div>
                    <div v-else>{{ scope2.row[head] }}</div>
                  </template>
                </el-table-column>
              </el-table>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    
    <!-- json复制内容弹窗 -->
    <el-dialog
      top="50px"
      :visible.sync="JsonCopyShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      :title="'JSON详情'"
    >
      <el-input
        class="copyJsonTextarea"
        ref="copyJsonTextarea_ref"
        type="textarea"
        readonly
        autosize
        resize="none"
        v-model="JsonCopyData"
      ></el-input>
    </el-dialog>

    <!-- details的table -->
    <el-dialog
      width="86%"
      v-if="detailTableRow"
      :visible.sync="detailsTableShow"
      :modal-append-to-body="true"
      :append-to-body="true"
      :show-close="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      :title="detailTableRow.name+' 详情'"
    >
      <umyTable
        :isShowIndex="true"
        :tableBorder="true"
        :setUTableHeight="240"
        :tableData="detailTableRow.value"
        :tableColumns="detailTableColumns"
        :selectionTable="false"
      ></umyTable>
    </el-dialog>
  </div>
</template>
<script>
import { LoadingMixins } from "@/mixins/LoadingMixins";
import { tableMixins } from "@/mixins/TableMixins"
export default {
  name:"showCopyJsonPop",
  mixins:[ LoadingMixins,tableMixins ],
  props: {
    // Json数据
    JsonData:{
      type: Object,
      default: null,
    },
  },
  data () {
    return {
      JsonTableShow:true,//点开查看Json转换后table弹窗
      JsonTableData:null,//表格转义的json数据
      JsonCopyData:null,//复制的Json字符串
      JsonCopyShow:false,//复制json的Dialog显隐控制
      detailTableHeader:null,//details表格的Header
      detailTableRow:null,//details的相关信息
      detailsTableShow:false,//details的详情
      detailTableColumns:false,//details的详情header表头
    }
  },
  mounted(){
    this.initJsonData()
  },
  methods: {
    // 关闭整个弹窗
    closePop() {
      this.JsonTableShow = false
      this.$emit("closePop")
    },
    // json数据转义
    initJsonData(){
      let _arr = []
      let __initJson = (data) => {
        let _init = []
        for(let item in data){
          _init.push({name:item,value:data[item]})
        }
        return _init
      }
      let _json = this.JsonData
      for(let item in _json){
        // 直接输出
        if(!_json[item]){
          _arr.push({name:item,value:_json[item]})
        }else{
          if(typeof _json[item] != 'object'){
            _arr.push({name:item,value:_json[item] + ""})
          }else{
              // 如果是数组
            if(Array.isArray(_json[item])){
              //  如果是 DETAILS todo:DETAILS判断条件需要优化，使用传参的方式
              // let _value = (item).toUpperCase() == 'DETAILS' ? __initJson(_json[item][0]) : (_json[item]).join(",")
              this.detailTableHeader = []
              for(let h in _json[item][0]){
                this.detailTableHeader.push(h)
              }
              let _value = (item).toUpperCase() == 'DETAILS' ? _json[item] : (_json[item]).join(",")
              _arr.push({name:item,value:_value})
            }
            // 如果是对象
            else{    
              let _obj_arr = __initJson(_json[item]) 
              // 对象有数据
              if(_obj_arr.length > 0){
                _arr = [..._obj_arr]
              }else{
                // 空对象
                _arr.push({name:item,value:""})
              }
            }
          }
        }
      }
      this.JsonTableData = _arr
      this.JsonCopyData = JSON.stringify(_json, null, '\t')//复制使用
    },
    // 复制后选择框处理
    copyJsonInputHandle(type){
      if(type == 'error')this.$message.error('复制失败');
      if(type == 'success')this.$message.success('复制成功');
      if(this.$refs.copyJsonTextarea_ref){
        this.$refs.copyJsonTextarea_ref.focus()
        this.$refs.copyJsonTextarea_ref.$refs.textarea.scrollTop = 0
      }
    },
    // 复制Json按钮
    copyJsonHandle(){
      this.JsonCopyShow = true
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(this.JsonCopyData)
          .then(() => {
            this.copyJsonInputHandle('success')
          })
          .catch(err => {
            this.copyJsonInputHandle('error')
          });
      }else {
        // 创建text area
        const textArea = document.createElement('textarea')
        textArea.value = this.JsonCopyData
        // 使text area不在viewport，同时设置不可见
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        return new Promise((resolve, reject) => {
            // 执行复制命令并移除文本框
            document.execCommand('copy') ? resolve() : reject(new Error('出错了'))
            textArea.remove()
        }).then(() => {
          this.$nextTick(()=>{
            this.copyJsonInputHandle('success')
          })
        },() => {
            this.copyJsonInputHandle('error')
        })
      }
      
    },
    // detail的table详情
    showDetailTableHandle(row){
      this.detailTableRow = row
      this.detailTableColumns = []
      this.detailTableHeader.forEach(item=>{
        this.detailTableColumns.push({
          prop:item,
          label:item
        })
      })
      this.detailsTableShow = true
    }
  }
}
</script>
<style lang="scss">
.copyJsonTextarea{
  textarea{
    max-height: calc(100vh - 220px) !important;
    overflow: auto !important;
  }
}
</style>