<template>
<!-- 去掉操作 -->
  <div>
    <div class="baseInfo_box">
      <div class="baseInfo">
        <bg-info :data="apiBaseInfo" />
      </div>
      <div class="apaas_button test_btn">
        <el-button type="primary" @click="serviceTest">
          <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-checklist"></bg-icon>
          服务测试
        </el-button>
      </div>
    </div>
    <div class="req_box">
      <el-tabs v-model="activeName">
        <el-tab-pane label="URL参数" name="first">
          <p class="input-title">
            <span class="before_title"></span>
            参数查询
            <span class="after_icon" @click="cs_open=!cs_open">
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-up" v-if="cs_open"></bg-icon>
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-down" v-else></bg-icon>
            </span>
          </p>
          <div v-if="cs_open">
            <bg-table-pro
              class="input_table"
              :headers="headers"
              :data="norData"
              ref="cs-table"
              :border="true"
              :stripe="false"
              v-if="norData && norData.length > 0"
            >
              <template v-slot:value="{ row }">
                <el-input
                  v-model="row.value"
                />
              </template>
            </bg-table-pro>
            <div class="no_data" v-else>
              <img src="../../assets/imgs/img-no-data.png" alt="">
              <div class="text">无参数</div>
            </div>
          </div>
          <p class="input-title mt">
            <span class="before_title"></span>
            动态参数
           <span class="after_icon" @click="dt_open=!dt_open">
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-up" v-if="dt_open"></bg-icon>
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-down" v-else></bg-icon>
           </span>
          </p>
          <div v-if="dt_open">
            <bg-table-pro
              class="input_table"
              :headers="headers"
              :data="actData"
              ref="dt-table"
              :border="true"
              :stripe="false"
              v-if="actData && actData.length > 0"
            >
              <template v-slot:value="{ row }">
                <el-input
                  v-model="row.value"
                />
              </template>
            </bg-table-pro>
            <div class="no_data" v-else>
              <img src="../../assets/imgs/img-no-data.png" alt="">
              <div class="text">无参数</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="Header" name="second">
          <p class="input-title">
            <span class="before_title"></span>
              Header
            <span class="after_icon" @click="header_open=!header_open">
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-up" v-if="header_open"></bg-icon>
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-down" v-else></bg-icon>
            </span>
          </p>
          <div v-if="header_open">
            <bg-table-pro
              :headers="headers"
              :data="headerData"
              ref="header-table"
              :border="true"
              :stripe="false"
              v-if="headerData && headerData.length > 0"
            >
              <template v-slot:value="{ row }">
                <el-input
                  v-model="row.value"
                />
              </template>
            </bg-table-pro>
            <div class="no_data" v-else>
              <img src="../../assets/imgs/img-no-data.png" alt="">
              <div class="text">无参数</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="body" name="third">
          <p class="input-title">
            <span class="before_title"></span>
              Body
            <span class="after_icon" @click="body_open=!body_open">
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-up" v-if="body_open"></bg-icon>
              <bg-icon style="font-size: 8px; color: #000;" icon="#bg-ic-arrow-down" v-else></bg-icon>
            </span>
          </p>
          <div v-if="body_open">
            <!-- raw -->
            <div v-if="bodyData && bodyData.show_type === 0 && bodyData.data && bodyData.data.length > 0" class="body_code" :style="{'height':bodyData.data_type === 1 || bodyData.data_type === 2 ? '406px' : '240px'}">
              <!-- json或xml展示代码块 -->
              <bg-code-editor
                class="bg-ace-editor"
                v-model="bodyData.data"
                v-if="bodyData.data_type === 1 || bodyData.data_type === 2"
              ></bg-code-editor>
              <!-- text或html或JavaScript展示多行文本框 -->
              <el-input
                v-model="bodyData.data"
                :rows="10"
                type="textarea"
                v-else
              />
            </div>
            <!-- formdata和x-www-form-urlencoded 表格 -->
            <bg-table-pro
              :headers="headers"
              :data="bodyData.data"
              ref="body-table"
              :border="true"
              :stripe="false"
              v-else-if="bodyData && (bodyData.show_type === 1 || bodyData.show_type === 2) && bodyData.data && bodyData.data.length > 0"
            >
              <template v-slot:value="{ row }">
                <el-input
                  v-model="row.value"
                />
              </template>
            </bg-table-pro>
            <div class="no_data" v-else>
              <img src="../../assets/imgs/img-no-data.png" alt="">
              <div class="text">无参数</div>
            </div>
          </div>

        </el-tab-pane>
        <el-tab-pane label="授权" name="fourth">
          <folder :data="detail_data" useType="service" :disabled="true"></folder>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="req_box res_box" v-if="test_state">
      <el-tabs v-model="activeName1">
        <el-tab-pane label="body" name="first">
          <div class="body_code">
            <bg-code-editor
              class="bg-ace-editor bg-ace-editor-disabled"
              v-model="backJSONdata"
              disabled
            ></bg-code-editor>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

  </div>
</template>

<script setup>
import { reactive, ref,onBeforeMount,toRefs,getCurrentInstance  } from 'vue'
import { useRouter,useRoute } from 'vue-router'
import folder from "@/page/main/ability-register/step2/folder.vue"
const { proxy } = getCurrentInstance()
const { $axios,$message } = proxy
const props = defineProps({
  data: {
    type: Object,
    default: null
  }
})
const emit = defineEmits(["serviceTest"])
const router = useRouter()
const route = useRoute()
const detailData = reactive({
  cs_open: true,
  dt_open: true,
  header_open: true,
  body_open: true,
  res_body_open: true,
  activeName: "first",
  apiBaseInfo: [
    {
      name: "接口名称",
      value: "",
      nameWidth: 104
    },
    {
      name: "调用地址",
      value: "",
      nameWidth: 104
    },
    {
      name: "请求方式",
      value: "",
      nameWidth: 104
    },
    {
      name: "返回格式",
      value: "",
      nameWidth: 104
    },
  ], // 基本信息
  headers: [
    {
      label: "键",
      prop: "name",
    },
    {
      label: "值",
      prop: "value",
    },
    {
      label: "描述",
      prop: "desc",
    },
  ], // 表头
  rawHeaders: [
    {
      label: "参数名称",
      prop: "paramName",
    },
    {
      label: "参数类型",
      prop: "paramType",
    },
    {
      label: "示例",
      prop: "paramValue",
    },
    {
      label: "说明",
      prop: "desc",
    },
  ],
  bodyData: {
    show_type: "",
    data_type: "",
    data: []
  },
  norData: [],
  actData: [],
  headerData: [],
  backJSONdata: "hahahaah",
  treeProps: { hasChildren: 'hasChildren', children: 'children' },
  rowKey: "id",
  detail_data: {},
  test_state: false,
  activeName1: "first"
})
const detail = props.data
detailData.detail_data = props.data
let serviceInfo = detail.service_info
//json对象转xml字符串
var json2xml=(o, tab)=> {
  var toXml = function(v, name, ind) {
    var xml = "";
    if (v instanceof Array) {
      for (var i=0, n=v.length; i<n; i++)
        xml += ind + toXml(v[i], name, ind+"\t") + "\n";
    }
    else if (typeof(v) == "object") {
      var hasChild = false;
      xml += ind + "<" + name;
      for (var m in v) {
        if (m.charAt(0) == "@")
          xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
        else
          hasChild = true;
      }
      xml += hasChild ? ">" : "/>";
      if (hasChild) {
        for (var m in v) {
          if (m == "#text")
            xml += v[m];
          else if (m == "#cdata")
            xml += "<![CDATA[" + v[m] + "]]>";
          else if (m.charAt(0) != "@")
            xml += toXml(v[m], m, ind+"\t");
        }
        xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">";
      }
    }
    else {
      xml += ind + "<" + name + ">" + v.toString() +  "</" + name + ">";
    }
    return xml;
  }, xml="";
   for (var m in o)
    xml += toXml(o[m], m, "");
   return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
}
if (detail) {
  detailData.apiBaseInfo[0].value = detail.service_name
  detailData.apiBaseInfo[1].value = detail.req_url
  detailData.apiBaseInfo[2].value = ['','GET','POST','PUT','DELETE'][detail.req_type]
  detailData.apiBaseInfo[3].value = ['','JSON','XML','Text','HTML','图片','文件','自动'][detail.res_fields.res_type]
  detailData.norData = detail.req_query.query_data || []
  detailData.actData = detail.req_query.param_data || []
  detailData.headerData = detail.req_headers
  detailData.bodyData = detail.req_body 
  let tableRows = detailData.bodyData && detailData.bodyData.data ? detailData.bodyData.data : []
  let tableStr = JSON.stringify(tableRows)
  if (detailData.bodyData && detailData.bodyData.show_type == 0 && detailData.bodyData.data_type == 1) {
    detailData.bodyData.data = tableStr
  }else if (detailData.bodyData && detailData.bodyData.show_type == 0 && detailData.bodyData.data_type == 2) {
    detailData.bodyData.data = json2xml(JSON.parse(tableStr))
  }
}
const serviceTest = () => {
  let header = null
  if (detail.headers && detail.headers.length > 0) {
    detail.req_headers.forEach((e,i) => {
      header[e.name] = [e.value]
    })
  }
  let body = ""
  if (detailData.bodyData.show_type == 0 && detailData.bodyData.data_type == 1 || detailData.bodyData.show_type == 1 || detailData.bodyData.show_type == 2) {
    body = detailData.bodyData.data && detailData.bodyData.data.length > 0 ? JSON.stringify(detailData.bodyData.data) : ""
  }else {
    body = detailData.bodyData.data && detailData.bodyData.data.length > 0? detailData.bodyData.data : ""
  }
  let show_type = detailData.bodyData.show_type
  let data_type = detailData.bodyData.data_type
  let content_type = ""
  if (show_type == 0) {
    switch (data_type) {
      case 1:
        content_type = "application/json";
        break;
      case 2: 
        content_type = "application/xml";
        break;
      case 3: 
        content_type = "application/javascript";
        break;
      case 4: 
        content_type = "text/plain";
        break;
      case 5: 
        content_type = "text/html";
        break;
    }
  }
  let authData = {
    req_auth_method: null,
    req_auth_token: "",
    req_auth_token_name: "",
  }
  let code = detail.ability_tree_code
  if (detail.req_auth_method != 0) {
    authData.req_auth_method = detail.req_auth_method
    authData.req_auth_token= detail.req_auth_token
    authData.req_auth_token_name= detail.req_auth_key
  }else {
    for (let index = 0; index > -1; index++) {
      if(serviceInfo[code].req_auth_method==0){
        code = serviceInfo[code].p_code
      }else{
        authData.req_auth_method = serviceInfo[code].req_auth_method
        authData.req_auth_token= serviceInfo[code].req_auth_token
        authData.req_auth_token_name= serviceInfo[code].req_auth_key
        break
      }
    }
  }
  let params = {
    interface_type: 1,
    method: detail.req_type,
    url: detail.req_url,
    req_auth_method: authData.req_auth_method,
    req_auth_token: authData.req_auth_token,
    req_auth_token_name: authData.req_auth_token_name,
    headers: header,
    body: body,
    content_type: content_type,
    id: detail.id.toString(),
    params: {
      query_data: detailData.norData,
      param_data: detailData.actData,
    }
  }
  $axios
    .post(`/apaas/service/v5/service/test`,params)
    .then((res) => {
      if (res.data.code !== 200) {
        $message.error(res.data.data)
      } else {
        detailData.test_state = true
        detailData.backJSONdata = res.data.data.response_str
        emit("refresh",detail.ability_tree_code)
      }
    })
}
const {
  cs_open,
  dt_open,
  header_open,
  body_open,
  res_body_open,
  headers,
  apiBaseInfo,
  activeName,
  activeName1,
  norData,
  actData,
  headerData,
  JSONdata,
  XMLdata,
  JSdata,
  Textdata,
  HTMLdata,
  backJSONdata,
  rawHeaders,
  bodyData,
  treeProps,
  rowKey,
  detail_data,
  test_state,
} = toRefs(detailData)
</script>

<style lang="scss" scoped>
.baseInfo_box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .baseInfo {
    width: 872px;
  }
}
.req_box {
  width: 872px;
  margin-top: 30px;
  .input-title {
    font-size: 16px;
    color: #202531;
    margin-top: 9px;
    margin-bottom: 15px;
    font-weight: 700;
    line-height: 1;
    .before_title {
      display: inline-block;
      width: 4px;
      height: 14px;
      background-color: #2b4695;
      margin-right: 8px;
      border-radius: 2px;
    }
    .after_icon {
      float: right;
      cursor: pointer;
    }
  }
  .mt {
    margin-top: 24px;
  }
  .input_table {
    :deep().el-table__cell {
      padding: 14px 0!important;
      .el-input__inner {
        height: 33px;
      }
    }
  }
  .text_box {
    padding: 16px 24px;
    background-color: #fafafa;
    border-radius: 4px;
    height: 406px;
  }
  .body_code {
    width: 100%;
    height: 406px;
    .bg-ace-editor {
      background-color: #1a1a1a;
    }
    .bg-ace-editor-disabled {
      background-color: #fff;
      :deep().ace_marker-layer .ace_active-line {
        background-color: #fff;
      }
    }
  }
  .no_data {
    text-align: center;
    .text {
      font-size: 16px;
      color: #616f94;
      line-height: 1;
    }
  }
  .folder-container {
    width: 100%;
    margin-left: 0;
    margin-top: 9px;
    :deep().left-span {
      padding: 0;
    }
    :deep().right-container {
      width: calc(100% - 100px);
    }
  }
}
</style>
<style scoped>

</style>
