<template>
  <div>
    {{myapi}}
    <el-row>
      <el-col :span="24"><div class="grid-content bg-purple-dark">
        <el-form  ref="form" :model="myapi" label-width="120px" :rules="rules">
          <el-form-item label="产品名称:" >
            {{myapi.productName}}
          </el-form-item>
          <el-form-item label="产品价格:">
            {{myapi.productPrice}}元/次
          </el-form-item>
          <el-form-item label="产品介绍:">
            {{myapi.productContent}}
          </el-form-item>
          <el-form-item label="重要路由:">
            {{myapi.apiRouter}}
          </el-form-item>

          <el-row>
            <el-col :span="24"><div class="grid-content bg-purple-dark">
              <span v-if="myapi.remark=='是'">
                <el-button type="info" @click="test(myapi)">立即使用</el-button>
                <el-button type="primary" @click="apply(myapi)">续约</el-button>
              </span>
              <span v-if="myapi.remark=='否'">
                <el-button type="info" @click="test(myapi)">测试</el-button>
                <el-button type="primary" @click="apply(myapi)">立即申请</el-button>
              </span>

            </div></el-col>
          </el-row>
        </el-form>
      </div></el-col>
    </el-row>
    <el-divider></el-divider>


    <el-row  class="first-row" >
      <el-col :span="24"><div class="grid-content bg-purple-dark" >
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="API文档" name="first">
            <el-form  ref="form" :model="myapi" label-width="120px" :rules="rules">
              <el-form-item label="接口地址:" >
                {{myapi.apiAddress}}
              </el-form-item>
              <el-form-item label="返回格式:">
                {{myapi.returnFormat}}
              </el-form-item>
              <el-form-item label="请求方式:">
                {{myapi.requestMethod}}
              </el-form-item>
              <el-form-item label="请求Header:">
                <el-table
                  :data="heanderData"
                  style="width: 100%">
                  <el-table-column
                    label="名称"
                    width="180">
                    <template slot-scope="scope">
                      <el-popover trigger="hover" placement="top">
                        <div slot="reference" class="name-wrapper">
                          {{scope.row.headerName}}
                        </div>
                      </el-popover>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="值"
                    width="250">
                    <template slot-scope="scope">
                      <el-popover trigger="hover" placement="top">
                        <div slot="reference" class="name-wrapper">
                          {{scope.row.headerValue}}
                        </div>
                      </el-popover>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item label="请求参数说明:">
                <el-table
                  :data="requestData"
                  style="width: 100%">
                  <el-table-column
                    label="参数名称"
                    width="180">
                    <template slot-scope="scope">
                      <el-popover trigger="hover" placement="top">
                        <div slot="reference" class="name-wrapper">
                          {{scope.row.requestName}}
                        </div>
                      </el-popover>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="参数类型"
                    width="250">
                    <template slot-scope="scope">
                      <el-popover trigger="hover" placement="top">
                        <div slot="reference" class="name-wrapper">
                          {{scope.row.requestType}}
                        </div>
                      </el-popover>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="是否必填"
                    width="250">
                    <template slot-scope="scope">
                      <el-popover trigger="hover" placement="top">
                        <div slot="reference" class="name-wrapper">
                          {{scope.row.requestIfmust}}
                        </div>
                      </el-popover>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="说明"
                    width="250">
                    <template slot-scope="scope">
                      <el-popover trigger="hover" placement="top">
                        <div slot="reference" class="name-wrapper">
                          {{scope.row.requestContent}}
                        </div>
                      </el-popover>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>



              <el-form-item label="返回参数说明:">

              </el-form-item>
              <el-form-item label="JSON返回示例:">

              </el-form-item>
              <el-form-item label="XML返回示例:">

              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="错误码参照" name="second">错误码参照</el-tab-pane>
          <el-tab-pane label="数据统计" name="third">数据统计</el-tab-pane>
        </el-tabs>
      </div></el-col>
    </el-row>

    <!--测试对话框-->
    <el-dialog
      title="接口测试"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="接口名称" prop="pass">
          <el-input type="text" v-model="ruleForm.productName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="接口地址" prop="pass">
          <el-input type="text" v-model="ruleForm.apiAddress" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="请求方式" prop="pass">
          <el-input type="text" v-model="ruleForm.requestMethod" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="请求参数" prop="pass" v-if="ruleForm.productName=='手机号码归属地' && ruleForm.productName=='万年历'" >
          <el-input type="text" v-model="ruleForm.parameter" autocomplete="off"></el-input>
        </el-form-item>
        <div v-if="ruleForm.productName=='新闻头条'">
          <el-form-item label="type" prop="pass" >
            <el-input type="text" v-model="ruleForm.type" autocomplete="off"></el-input>
            <span>说明：支持类型top(推荐,默认)guonei(国内)guoji(国际)yule(娱乐)tiyu(体育)junshi(军事)keji(科技)caijing(财经)youxi(游戏)qiche(汽车)jiankang(健康)</span>
          </el-form-item>
          <el-form-item label="page" prop="pass" >
            <el-input type="text" v-model="ruleForm.page" autocomplete="off"></el-input>
            <span>说明：当前页数, 默认1, 最大50</span>
          </el-form-item>
          <el-form-item label="page_size" prop="pass" >
            <el-input type="text" v-model="ruleForm.pageSize" autocomplete="off"></el-input>
            <span>说明：每页返回条数, 默认30 , 最大30</span>
          </el-form-item>
          <el-form-item label="is_filter" prop="pass" >
            <el-input type="text" v-model="ruleForm.isFilter" autocomplete="off"></el-input>
            <span>说明：是否只返回有内容详情的新闻, 1:是, 默认0</span>
          </el-form-item>
        </div>
        <div v-if="ruleForm.productName=='身份证实名认证'">
          <el-form-item label="身份证号码" prop="pass"  >
            <el-input type="text" v-model="ruleForm.idcard" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="pass">
            <el-input type="text" v-model="ruleForm.realname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="是否返回单号" prop="pass" >
            <el-input type="text" v-model="ruleForm.orderid" autocomplete="off"></el-input>
            <span>传1时返回单号，默认不返回单号(建议传入)</span>
          </el-form-item>
        </div>
        <!--一个参数-->
        <el-form-item v-if="ruleForm.productName=='手机号码归属地' && ruleForm.productName=='万年历'">
          <el-button type="primary" @click="submitForm(ruleForm)">发送请求</el-button>
        </el-form-item>
        <!--多个参数-->
        <el-form-item  v-if="ruleForm.productName=='新闻头条' ||ruleForm.productName=='身份证实名认证' " >npm
          <el-button type="primary" @click="newsForm(ruleForm)">发送请求</el-button>
        </el-form-item>
        <!--无参数-->
        <el-form-item  v-if="ruleForm.productName=='朋友圈文案'" >
          <el-button type="primary" @click="noForm(ruleForm)">发送请求</el-button>
        </el-form-item>
      </el-form>
      <pre id="json-display">

      </pre>
      <ul id="news-list">
        <!-- 这里将动态插入新闻项 -->
      </ul>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">返回</el-button>
  </span>
    </el-dialog>


    <!--支付规格选择对话框-->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible1"
      width="50%"
      :before-close="handleClose1">


      <span style="color: #1ab394">请选择申请规格</span>
      <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
          label="支付规格"
          width="180">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <div slot="reference" class="name-wrapper">
                <el-button >包年</el-button>
                <el-tag size="medium">{{ scope.row.productSpecificationName }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          label="价格"
          width="180">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.middlePrice }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider></el-divider>
      <el-form  ref="form" :model="newapi" label-width="120px" :rules="rules">
        <el-form-item label="产品名称:" >
          {{newapi.productName}}
        </el-form-item>
        <el-form-item label="产品规格:" >
          {{newapi.productSpecification}}
        </el-form-item>
        <el-form-item label="产品价格:" v-if="newapi.productSpecification=='按次查询'">
          {{newapi.productPrice}}元/次
        </el-form-item>
        <el-form-item label="支付价格:" v-if="newapi.productSpecification!='按次查询'">
          {{newapi.productPrice}}元
        </el-form-item>
        <el-form-item label="产品介绍:">
          {{newapi.productContent}}
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible1 = false">取 消</el-button>
    <el-button type="primary" @click=" confirmSelection(row)">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
//例如：import 《组件名称》 from '《组件路径》,
import {
  findcount,
  getHeader, getRequest,
  iftest,
  reducetestcount,
  sendrequest,
  sendrequest1,
  sendrequest2
} from "@/api/apitest/apitest";
import api from "js-cookie";
import {companyauthentication, ifcompanyauthentication} from "@/api/authentication/authentication";
import {selectproductspecification} from "@/api/market/product";
import myapi from "@/views/market/myapi/index.vue";

export default {
    name: "Apitest",
    //import引入的组件需要注入到对象中才能使用"
    components: {},
    props: {},
    data() {
      //这里存放数据"

      return {
        myapi: {
          productName: '',
          productPrice: '',
          productContent: ''
        },
        activeName: 'first',
        dialogVisible: false,
        dialogVisible1: false,
        ruleForm:{},
        tableData:[],
        newapi:{},
        //请求头部
        heanderData:[],
        //请求参数
        requestData:[]
      };
    },
    //计算属性 类似于data概念",
    computed: {},
    //监控data中的数据变化",
    watch: {},
    //方法集合",
    methods: {
      //获取请求头部
      getHeader(myapi){
        getHeader(myapi).then(response=>{
          this.heanderData=response.data
        })
      },
      //获取请求参数

      getRequest(myapi){
        getRequest(myapi).then(response=>{
          this.requestData=response.data
        })
      },
      //标签页
      handleClick(tab, event) {
        console.log(tab, event);
      },
      //测试
      test(myapi){
        //判断测试次数是否<=0
        findcount(myapi).then(response=>{
          alert(response.data.testCount)
          if (response.data.testCount<=0){
              alert("使用次数已到期,若像继续使用请先充值！")
          }else{
            this.dialogVisible=true
            this.ruleForm={
              productName: myapi.productName,
              apiAddress: myapi.apiAddress,
              requestMethod: myapi.requestMethod,
              apiRouter: myapi.apiRouter
            }
          }
        })

      },
      //立即申请
      apply(myapi){
        //先判断是否已经进行了认证
        ifcompanyauthentication().then(response=>{
          if (response.code!=200){
            alert(response.msg)
          }else {
            this.getproduct(myapi)
            this.dialogVisible1=true
            this.newapi={
              productName: myapi.productName,
              productPrice: myapi.productPrice,
              productContent: myapi.productContent,
              productSpecification: myapi.productSpecification
            }
          }
        })
      },
      //关闭测试对话框
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //关闭支付规格选择对话框
      handleClose1(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //产品规格
      getproduct(specification){
        selectproductspecification(specification).then(response=>{
          this.tableData=response.data
        })
      },
      //选择申请规格
      handleEdit(row){
        this.newapi={
          productName:this.myapi.productName,
          productSpecification: row.productSpecificationName,
          productPrice: row.middlePrice,
          productContent:this.myapi.productContent,
        }
      },
      //测试发送请求 无参数
      noForm(ruleForm){
        sendrequest2(ruleForm).then(response=>{
          console.log(response)
          const jsonData1 = response.data; // 假设response.data是解析后的JSON对象

          // 解析JSON字符串为JavaScript对象
          const jsonData = JSON.parse(jsonData1);

          // 创建一个容器来展示数据
          var container = document.getElementById('news-list');
          // 清空容器内容
          container.innerHTML = '';

          // 创建一个div来存放结果
          var resultDiv = document.createElement('div');

          // 检查jsonData.reason
          if (jsonData.reason !== undefined) {
            // 移除reason中的感叹号（如果存在）
            resultDiv.innerHTML += '<h2>Reason: ' + jsonData.reason.replace(/!/g, '') + '</h2>';
          } else {
            resultDiv.innerHTML += '<h2>Reason: Not available</h2>';
          }
          // 检查jsonData.result
          if (jsonData.result !== undefined) {
            // 添加result中的信息，但使用正确的字段名
            resultDiv.innerHTML += '<p>Content: ' + jsonData.result.content + '</p>';
            resultDiv.innerHTML += '<p>Source: ' + jsonData.result.source + '</p>';
            // 注意：原始JSON中没有realname, idcard, orderid, res这些字段
          } else {
            resultDiv.innerHTML += '<p>Result information is not available.</p>';
          }
          // 将结果div添加到容器中
          container.appendChild(resultDiv);
        })
        //测试次数-1
        reducetestcount(this.myapi).then(response=>{})
      },
      //测试发送请求 单个参数
      submitForm(ruleForm){
        sendrequest(ruleForm).then(response=>{
          const jsonData = response.data;
          // 使用JSON.stringify()来格式化JSON数据，并设置缩进为2个空格
          const formattedJson = JSON.stringify(jsonData, null, 2);
          // 获取<pre>元素并设置其innerHTML为格式化的JSON字符串
          document.getElementById('json-display').innerHTML = formattedJson;
        })

        //测试次数-1
          reducetestcount(this.myapi).then(response=>{
          })

      },
      //测试发送请求 多个参数
      newsForm(ruleForm) {
        if (ruleForm.productName=='新闻头条'){
          sendrequest1(ruleForm).then(response => {
            console.log(response)
            const jsonData1 = response.data; // 假设response.data是解析后的JSON对象

            // 解析JSON字符串为JavaScript对象
            const jsonData = JSON.parse(jsonData1);

            // 创建一个容器来展示数据
            var container = document.getElementById('news-list');
            // 清空容器内容
            container.innerHTML = '';

            // 创建一个div来存放结果
            var resultDiv = document.createElement('div');

            // 检查jsonData.reason
            if (jsonData.reason !== undefined) {
              // 移除reason中的感叹号（如果存在）
              resultDiv.innerHTML += '<h2>Reason: ' + jsonData.reason.replace(/!/g, '') + '</h2>';
            } else {
              resultDiv.innerHTML += '<h2>Reason: Not available</h2>';
            }
            // 检查jsonData.result
            if (jsonData.result !== undefined) {
              // 添加其他结果信息
              resultDiv.innerHTML += '<p>Stat: ' + jsonData.result.stat + '</p>';
              resultDiv.innerHTML += '<p>Page: ' + jsonData.result.page + '</p>';
              resultDiv.innerHTML += '<p>Page Size: ' + jsonData.result.pageSize + '</p>';

              // 检查jsonData.result.data
              if (Array.isArray(jsonData.result.data)) {
                // 遍历数据并生成HTML
                jsonData.result.data.forEach(item => {
                  resultDiv.innerHTML += `
          <div>
            <h3>${item.title}</h3>
            <p>Unique Key: ${item.uniquekey}</p>
            <p>Date: ${item.date}</p>
            <p>Category: ${item.category}</p>
            <p>Author: ${item.author_name}</p>
            <p>URL: <a href="${item.url.replace(/\\/g, '')}">${item.url}</a></p>
          </div>
        `;
                });
              } else {
                resultDiv.innerHTML += '<p>No data available.</p>';
              }
            } else {
              resultDiv.innerHTML += '<p>Result information is not available.</p>';
            }

            // 将结果div添加到容器中
            container.appendChild(resultDiv);

          });
        }
        if (ruleForm.productName=='身份证实名认证'){
          sendrequest1(ruleForm).then(response => {
            console.log(response)
            const jsonData1 = response.data; // 假设response.data是解析后的JSON对象

            // 解析JSON字符串为JavaScript对象
            const jsonData = JSON.parse(jsonData1);
        });
      }},
      confirmSelection(row) {
        if (this.selectedRow) {

          // 这里假设你有一个发起支付的方法，传入所选行的数据
          // startPayment(this.selectedRow);
          console.log(row)
          window.open("http://21.12.0.10:80/prod-api/market/alipay/pay?ordersPrice=" + row.middlePrice)
          this.$message.success('付款成功')
        }

      },

show(){
        // 创建一个容器来展示数据
        var container = document.getElementById('news-list');
        // 清空容器内容
        container.innerHTML = '';

        // 创建一个div来存放结果
        var resultDiv = document.createElement('div');

        // 检查jsonData.reason
        if (jsonData.reason !== undefined) {
          // 移除reason中的感叹号（如果存在）
          resultDiv.innerHTML += '<h2>Reason: ' + jsonData.reason.replace(/!/g, '') + '</h2>';
        } else {
          resultDiv.innerHTML += '<h2>Reason: Not available</h2>';
        }
        // 检查jsonData.result
        if (jsonData.result !== undefined) {
          // 添加result中的信息
          resultDiv.innerHTML += '<p>Real Name: ' + jsonData.result.realname + '</p>';
          resultDiv.innerHTML += '<p>ID Card: ' + jsonData.result.idcard + '</p>';
          resultDiv.innerHTML += '<p>Order ID: ' + jsonData.result.orderid + '</p>';
          resultDiv.innerHTML += '<p>Result: ' + jsonData.result.res + '</p>';
        } else {
          resultDiv.innerHTML += '<p>Result information is not available.</p>';
        }

        // 将结果div添加到容器中
        container.appendChild(resultDiv);

        //测试次数-1
        reducetestcount(this.myapi).then(response=>{})
      }

    },
    //生命周期 - 创建完成（可以访问当前this实例）",
    created() {
    },
    //生命周期 -` 挂载完成（可以访问DOM元素）",
    mounted() {
      this.myapi = this.$route.query.myapi
      this.getHeader(this.myapi)
      this.getRequest((this.myapi))
      if (typeof this.myapi === 'string' && this.myapi.trim() !== '') {
        try {
          this.myapi = JSON.parse(this.myapi);
        } catch (error) {
          console.error('Failed to parse JSON:', error);
          // 可以设置一个错误处理逻辑，比如将 myapi 设置为空对象
          this.myapi = {};
        }
      }
    },
    beforeCreate() {
    }, //生命周期 - 创建之前",
    beforeMount() {
    }, //生命周期 - 挂载之前",
    beforeUpdate() {
    }, //生命周期 - 更新之前",
    updated() {
    }, //生命周期 - 更新之后",
    beforeDestroy() {
    }, //生命周期 - 销毁之前",
    destroyed() {
    }, //生命周期 - 销毁完成",
    activated() {
    } //如果页面有keep-alive缓存功能，这个函数会触发",
  };
</script>
<style scoped>
.first-row {
  margin-bottom: 20px; /* 创建一个空间，以便可以清晰地看到边框 */
}
pre {
  background-color: #f4f4f4; /* 浅灰色背景 */
  border: 1px solid #ddd; /* 边框 */
  padding: 10px; /* 内边距 */
  overflow-x: auto; /* 水平滚动条（如果需要的话） */
  white-space: pre-wrap; /* 保留空白符序列，但是正常地进行换行 */
  word-wrap: break-word; /* 防止长单词或URL地址破坏布局 */
  font-family: monospace, Menlo, Courier, 'Courier New', monospace; /* 使用等宽字体 */
}
</style>
