<template>
  <div class="app-container">
    <el-form :model="form" ref="form">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入步骤名称"/>
      </el-form-item>
      <el-form-item label="接口" prop="uri">
        <template type="label">
          <el-button type="text" size="mini" @click="() => this.open = true">引用接口</el-button>
        </template>
        <el-input placeholder="请输入接口路径" v-model="form.requestUrl" class="input-with-select">
          <el-select v-model="form.requestMethod" slot="prepend">
            <el-option v-for="dict in dict.type.http_method" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label="主机" prop="apiHttpId">
        <el-select v-model="form.apiHttpId" style="width: 100%;" clearable @change="apiHttpIdHandleChange">
          <el-option v-for="item in this.hosts" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="协议" prop="apiProtocol">
            <el-select v-model="form.apiProtocol" style="width: 100%;" :disabled="!!form.apiHttpId">
              <el-option v-for="dict in dict.type.http_protocol" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="主机地址" prop="apiHost">
            <el-input v-model="form.apiHost" placeholder="请输入主机地址" :disabled="!!form.apiHttpId"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="端口号" prop="apiPort">
            <el-input v-model="form.apiPort" placeholder="请输入端口号" :disabled="!!form.apiHttpId"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="activeName">
      <el-tab-pane label="Headers" name="Headers">
        <el-table :data="form.requestHeader">
          <el-table-column label="参数名">
            <template slot-scope="scope">
              <el-input placeholder="请输入参数名" v-model="form.requestHeader[scope.$index].key" @input="e => handleTableEdit(e, 'header', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="示例值">
            <template slot-scope="scope">
              <el-input placeholder="请输入参数名" v-model="form.requestHeader[scope.$index].value" @input="e => handleTableEdit(e, 'header', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-button v-if="form.requestHeader.length > scope.$index+1" size="mini" type="text" icon="el-icon-delete" @click="handleDelete('header', scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="Params" name="Params">
        <el-table :data="form.requestParams">
          <el-table-column label="参数名">
            <template slot-scope="scope">
              <el-input placeholder="请输入参数名" v-model="form.requestParams[scope.$index].key" @input="e => handleTableEdit(e, 'param', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="示例值">
            <template slot-scope="scope">
              <el-input placeholder="请输入示例值" v-model="form.requestParams[scope.$index].value" @input="e => handleTableEdit(e, 'param', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-button v-if="form.requestParams.length > scope.$index+1" size="mini" type="text" icon="el-icon-delete" @click="handleDelete('param', scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="Body" name="Body">
        <JsonEditorVue mode="text" v-model="form.requestBody" class="jse-theme-dark"/>
      </el-tab-pane>
      <el-tab-pane label="提取" name="assignment">
        <el-table :data="form.assignment">
          <el-table-column label="变量名">
            <template slot-scope="scope">
              <el-input placeholder="请输入变量名" v-model="form.assignment[scope.$index].name" @input="e => handleTableEdit(e, 'assignment', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="提取方式">
            <template slot-scope="scope">
              <el-select v-model="form.assignment[scope.$index].type" style="width: 100%;" placeholder="请选择提取方式">
                <el-option v-for="dict in dict.type.extract_type" :key="dict.value" :label="dict.label" :value="dict.value" @change="e => handleTableEdit(e, 'assignment', scope)"/>
              </el-select>
<!--              <el-input placeholder="请输入提取方式" v-model="form.assignment[scope.$index].type" @input="e => handleTableEdit(e, 'assignment', scope)" clearable/>-->
            </template>
          </el-table-column>
          <el-table-column label="提取对象">
            <template slot-scope="scope">
              <el-select v-model="form.assignment[scope.$index].content" style="width: 100%;" placeholder="请选择提取对象">
                <el-option v-for="dict in extract_object" :key="dict.value" :label="dict.label" :value="dict.value" @change="e => handleTableEdit(e, 'assignment', scope)"/>
              </el-select>
<!--              <el-input placeholder="请输入提取对象" v-model="form.assignment[scope.$index].content" @input="e => handleTableEdit(e, 'assignment', scope)" clearable/>-->
            </template>
          </el-table-column>
          <el-table-column label="提取表达式">
            <template slot-scope="scope">
              <el-input placeholder="请输入提取表达式" v-model="form.assignment[scope.$index].path" @input="e => handleTableEdit(e, 'assignment', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-button v-if="form.assignment.length > scope.$index+1" size="mini" type="text" icon="el-icon-delete" @click="handleDelete('assignment', scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-collapse v-model="activeNames" accordion v-if="form.testCaseResultList" @change="handleLogChange">
          <el-collapse-item :title="itemSub.title" :name="itemSub.title" v-for="(itemSub, index) in form.testCaseResultList" :key="index">
            <el-tabs v-model="activeTabs">
              <el-tab-pane label="请求头" name="requestHeader">
                <codemirror v-model="resultLog.requestHeader" :options="editorOptions" v-if="resultLog.requestHeader"/>
              </el-tab-pane>
              <el-tab-pane label="请求体" name="requestBody">
                <codemirror v-model="resultLog.requestBody" :options="editorOptions" v-if="resultLog.requestBody"/>
              </el-tab-pane>
              <el-tab-pane label="响应头" name="responseHeader">
                <codemirror v-model="resultLog.responseHeader" :options="editorOptions" v-if="resultLog.responseHeader"/>
              </el-tab-pane>
              <el-tab-pane label="响应体" name="responseBody">
                <codemirror v-model="resultLog.responseBody" :options="editorOptions" v-if="resultLog.responseBody"/>
              </el-tab-pane>
            </el-tabs>
          </el-collapse-item>
        </el-collapse>
      </el-tab-pane>
      <el-tab-pane label="校验" name="assertion">
        <el-table :data="form.assertion">
          <el-table-column label="描述">
            <template slot-scope="scope">
              <el-input placeholder="请输入描述" v-model="form.assertion[scope.$index].name" @input="e => handleTableEdit(e, 'assertion', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="对象">
            <template slot-scope="scope">
              <el-select v-model="form.assertion[scope.$index].source" style="width: 100%;" filterable allow-create placeholder="请选择对象">
                <el-option v-for="dict in extract_object" :key="dict.value" :label="dict.label" :value="dict.value" @change="e => handleTableEdit(e, 'assertion', scope)"/>
              </el-select>
<!--              <el-input placeholder="请输入对象" v-model="form.assertion[scope.$index].source" @input="e => handleTableEdit(e, 'assertion', scope)" clearable/>-->
            </template>
          </el-table-column>
          <el-table-column label="条件">
            <template slot-scope="scope">
              <el-select v-model="form.assertion[scope.$index].fn" style="width: 100%;" placeholder="请选择条件">
                <el-option v-for="dict in dict.type.assert_condition" :key="dict.value" :label="dict.label" :value="dict.value" @change="e => handleTableEdit(e, 'assertion', scope)"/>
              </el-select>
<!--              <el-input placeholder="请输入条件" v-model="form.assertion[scope.$index].fn" @input="e => handleTableEdit(e, 'assertion', scope)" clearable/>-->
            </template>
          </el-table-column>
          <el-table-column label="内容">
            <template slot-scope="scope">
              <el-input placeholder="请输入内容" v-model="form.assertion[scope.$index].target" @input="e => handleTableEdit(e, 'assertion', scope)" clearable/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-button v-if="form.assertion.length > scope.$index+1" size="mini" type="text" icon="el-icon-delete" @click="handleDelete('assertion', scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="选择接口" :visible.sync="open" width="80%" append-to-body>
      <folder-page type="api" @click="folderHandleSelected" ref="folder">
        <div v-if="queryParams.groupId && queryParams.groupId !== 0">
          <el-table v-loading="loading" :data="apiList">
            <el-table-column label="接口名称" align="center" prop="name"/>
            <el-table-column label="接口请求类型" align="center" prop="method"/>
            <el-table-column label="接口路径" align="center" prop="uri"/>
            <el-table-column label="创建时间" align="center" prop="createTime"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="linkApi(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
        </div>
        <el-empty v-else />
      </folder-page>
    </el-dialog>
  </div>
</template>

<script>
import JsonEditorVue from "json-editor-vue";
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/mode/sql/sql"; // 语言模式
import "codemirror/theme/dracula.css";
import "codemirror/addon/display/autorefresh";
import {listHttp} from "@/api/test/http";
import FolderPage from "@/components/FolderPage/index.vue";
import {listApi} from "@/api/test/api";
import {getCaseStepResultLog} from "@/api/test/caseStep";

export default {
  components: {FolderPage, JsonEditorVue, codemirror},
  dicts: ['http_method', 'http_protocol','extract_type','assert_condition'],
  props: {
    form: {
      type: Object
    },
    hosts: {
      type: Array
    },
    quoteList: {
      type: Array
    }
  },
  created() {
    // 在这里进行数据预处理
    this.preProcessFormData();
  },
  mounted() {
    // 在组件挂载后调用方法
    this.appendNamesToExtractObject();
  },
  data() {
    return {
      activeName: "Headers",
      open: false,
      loading: false,
      total: 0,
      apiList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
      },
      extract_object: [{
        value: '${RESPONSE_BODY}',
        label: '${RESPONSE_BODY}'
      }, {
        value: '${RESPONSE_HEADER}',
        label: '${RESPONSE_HEADER}'
      }, {
        value: '${RESPONSE_CODE}',
        label: '${RESPONSE_CODE}'
      }],
      resultLog: {
        requestHeader: '',
        requestBody: '',
        responseHeader: '',
        responseBody: '',
        sqlResult: ''
      },
      activeNames: 'requestHeader',
      activeTabs: 'requestHeader',
      editorOptions: {
        autoRefresh: true,
        mode: "sql", // 代码语言
        theme: "dracula", // 主题
        lineNumbers: true, // 显示行号
        tabSize: 2
      }
    }
  },
  methods: {
    appendNamesToExtractObject() {
      if (this.quoteList) {
        this.quoteList.forEach(item => {
          item.assignment.forEach(item2 => {
            if (item2.name && !this.isDuplicate(item2.name)) {
              this.extract_object.push({
                value: '${' + item2.name + '}',
                label: '${' + item2.name + '}'
              });
            }
          });
        });
      }
    },
    isDuplicate(name) {
      let compareName = '${' + name + '}';
      return this.extract_object.some(obj => obj.value === compareName);
    },
    handleLogChange(val) {
      const selectedItem = this.form.testCaseResultList.find(item => item.title === val);
      if (selectedItem) {
        getCaseStepResultLog(selectedItem.id).then(res => {
          this.resultLog = res.data;
        });
      }
    },
    preProcessFormData() {
      if (typeof this.form.requestHeader === 'string') {
        try {
          this.form.requestHeader = JSON.parse(this.form.requestHeader);
        } catch (e) {
        }
      }
      if (typeof this.form.requestParams === 'string') {
        try {
          this.form.requestParams = JSON.parse(this.form.requestParams);
        } catch (e) {
        }
      }
      if (typeof this.form.assignment === 'string') {
        try {
          this.form.assignment = JSON.parse(this.form.assignment);
        } catch (e) {
        }
      }
      if (typeof this.form.assertion === 'string') {
        try {
          this.form.assertion = JSON.parse(this.form.assertion);
        } catch (e) {
        }
      }
    },
    folderHandleSelected(id) {
      if (id) {
        this.queryParams.groupId = id;
        this.getList();
      } else {
        this.apiList = [];
      }
    },
    getList() {
      this.loading = true;
      listApi(this.queryParams).then(response => {
        this.apiList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    linkApi(row) {
      this.open = false
      if (row) {
        this.form.requestMethod = row.method
        this.form.name = row.name
        this.form.requestUrl = row.uri
        this.form.requestBody = row.body
        if (row.header && JSON.parse(row.header).length) {
          this.form.requestHeader = JSON.parse(row.header);
          this.form.requestHeader.push([{
            key: "",
            value: "",
          }])
        } else {
          this.form.requestHeader = [{
            key: "",
            value: "",
          }]
        }

        if (row.param && JSON.parse(row.param).length) {
          this.form.requestParams = JSON.parse(row.param);
          this.form.requestParams.push([{}])
        } else {
          this.form.requestParams = [{
            key: "",
            value: "",
          }]
        }

        if (row.body) {
          this.form.requestBody = row.body;
        } else {
          this.form.requestBody = '';
        }
      }
    },
    apiHttpIdHandleChange(e) {
      let p = this.hosts.findLast(item => item.id === e)
      if (p) {
        this.form.apiHost = p.host;
        this.form.apiPort = p.port;
        this.form.apiProtocol = p.protocol;
        if (p.header) {
          let newHeader = JSON.parse(p.header);
          if (newHeader && newHeader.length > 0) {
            this.form.requestHeader = newHeader;
          } else {
            return;
          }
          this.form.requestHeader.push([{
            key: "",
            value: "",
          }])
        }
      } else {
        this.form.apiHttpId = undefined;
        this.form.apiHost = undefined;
        this.form.apiPort = undefined;
        this.form.apiProtocol = undefined;
      }
    },
    handleTableEdit(e, flag, scope) {
      if (flag === "header") {
        if (e && this.form.requestHeader.length === scope.$index + 1) {
          this.form.requestHeader.push({
            key: "",
            value: ""
          })
        }
      }
      if (flag === "param") {
        if (e && this.form.requestParams.length === scope.$index + 1) {
          this.form.requestParams.push({
            key: "",
            value: ""
          })
        }
      }
      if (flag === "assignment") {
        if (e && this.form.assignment.length === scope.$index + 1) {
          this.form.assignment.push({
            key: "",
            value: ""
          })
        }
      }
      if (flag === "assertion") {
        if (e && this.form.assertion.length === scope.$index + 1) {
          this.form.assertion.push({
            key: "",
            value: ""
          })
        }
      }
    },
    handleDelete(flag, scope) {
      if (flag === "header") {
        this.form.requestHeader.splice(scope.$index, 1)
      }
      if (flag === "param") {
        this.form.requestParams.splice(scope.$index, 1)
      }
      if (flag === "assignment") {
        this.form.assignment.splice(scope.$index, 1)
      }
      if (flag === "assertion") {
        this.form.assertion.splice(scope.$index, 1)
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-collapse-item__wrap {
  padding: 0 16px;
}

::v-deep.el-select {
  width: 130px;
}

.input-with-select ::v-deep .el-input-group__prepend {
  background-color: #fff;
}
::v-deep .el-container {
  height: unset;
}
</style>
