<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">
              <el-button type="info" @click="test(myapi)">测试</el-button>
              <el-button type="primary" @click="apply(myapi)">立即申请</el-button>
            </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="请求参数说明:">

              </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!=='新闻头条'" >
          <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>
        <el-form-item v-if="ruleForm.productName!=='新闻头条'">
          <el-button type="primary" @click="submitForm(ruleForm)">发送请求</el-button>
        </el-form-item>
        <el-form-item  v-if="ruleForm.productName=='新闻头条'">
          <el-button type="primary" @click="newsForm(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">
      <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-form>
      <el-divider></el-divider>
      <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-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>
      <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 {sendrequest, sendrequest1} from "@/api/apitest/apitest";
import api from "js-cookie";
import {companyauthentication, ifcompanyauthentication} from "@/api/authentication/authentication";
import {selectproductspecification} from "@/api/market/product";

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

      return {
        myapi: {
          productName: '',
          productPrice: '',
          productContent: ''
        },
        activeName: 'first',
        dialogVisible: false,
        dialogVisible1: false,
        ruleForm:{},
        tableData:[]
      };
    },
    //计算属性 类似于data概念",
    computed: {},
    //监控data中的数据变化",
    watch: {},
    //方法集合",
    methods: {
      api,
      //标签页
      handleClick(tab, event) {
        console.log(tab, event);
      },
      //测试
      test(myapi){
        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 {
            alert(JSON.stringify(myapi))
            this.getproductspecification(myapi)
            this.dialogVisible1=true

          }
        })
      },
      //关闭测试对话框
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //关闭支付规格选择对话框
      handleClose1(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //产品规格
      getproductspecification(specification){
        selectproductspecification(specification).then(response=>{
          this.tableData=response.data
        })
      },
      //测试发送请求 单个参数
      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;
        })
      },
      //测试发送请求 多个参数
      newsForm(ruleForm) {
        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);

        });
      },
      handleEdit(row) {
        this.selectedRow = row;
      },
      confirmSelection(row) {
        this.dialogVisible1=false
        if (this.selectedRow) {
          // 这里假设你有一个发起支付的方法，传入所选行的数据
          startPayment(this.selectedRow);
          console.log(row)
          window.open("http://localhost:9701/alipay/pay?middlePrice="+row.middlePrice)
          this.$message.success('付款成功')

          this.dialogVisible1 = false;

        } else {
          // 如果没有选择任何行，给出提示
          this.$message.warning('请先选择一项进行支付');
        }
      },
    },
    //生命周期 - 创建完成（可以访问当前this实例）",
    created() {
    },
    //生命周期 -` 挂载完成（可以访问DOM元素）",
    mounted() {
      this.myapi = this.$route.query.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>
