<template>
  <div>
    <el-form ref="caseFormRef" :rules="rules" :model="caseForm" label-width="90px">
      <el-form-item label="模块名称:" prop="moduleId">
        <el-select v-model="caseForm.moduleId" placeholder="请选择模块" @change="selectChangeModel" clearable>
          <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="接口名称:" prop="interfaceId">
        <el-select v-model="caseForm.interfaceId" placeholder="请选择接口" @change="selectChangeInterface" clearable>
          <el-option v-for="item in interfaceList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-card v-if="this.isShow">
        <el-form-item label="用例名称:" prop="name" style="width:310px;margin-left:-20px">
          <el-input v-model="caseForm.name" placeholder="请输入用例名称"></el-input>
        </el-form-item>
        <el-collapse v-model="activeNames">
          <!-- Headers -->
          <el-collapse-item name="1" title="请求头">
            <el-form-item>
              <el-row>
                <el-col :span="5">
                  <div class="grid-content" style="margin-left:100px">参数名称</div>
                </el-col>
                <el-col :span="8">
                  <div class="grid-content" style="margin-left:180px">参数值</div>
                </el-col>
                <el-col :span="2">
                  <div class="grid-content" style="margin-left:40px">操作</div>
                </el-col>
              </el-row>
              <el-row v-for="(item,index) in headersList" :key="index">
                <el-col :span="5">
                  <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                </el-col>
                <el-col :span="8">
                  <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值" type="textarea" autosize ></el-input>
                </el-col>
                <el-col :span="2">
                  <el-button size="mini" type="danger" @click="advanceDelss(index)" icon="el-icon-delete" style="height:40px;margin-left:20px">删除</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button type="primary" size="mini" plain @click="AddHeaderListRow()" style="margin-top:10px" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
          <!-- 请求参数 -->
          <el-collapse-item name="2" title="请求参数">
            <el-form-item>
              <el-row>
                <el-col :span="5">
                  <div class="grid-content" style="margin-left:100px">参数名称</div>
                </el-col>
                <el-col :span="8">
                  <div class="grid-content" style="margin-left:180px">参数值</div>
                </el-col>
                <el-col :span="2">
                  <div class="grid-content" style="margin-left:40px">操作</div>
                </el-col>
              </el-row>
              <el-row v-for="(item,index) in requestParamsList" :key="index">
                <el-col :span="5">
                  <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                </el-col>
                <el-col :span="8">
                  <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值" type="textarea" autosize></el-input>
                </el-col>
                <el-col :span="2">
                  <el-button size="mini" type="danger" @click="requestParamsDel(index)" icon="el-icon-delete" style="height:40px;margin-left:20px">删除</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button type="primary" size="mini" plain @click="AddRequestParamsListRow()" style="margin-top:10px" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
          <!-- 响应解析列表 -->
          <el-collapse-item name="3" title="响应提取">
            <el-form-item>
              <el-row>
                <el-col :span="5">
                  <div class="grid-content" style="margin-left:100px">变量名称</div>
                </el-col>
                <el-col :span="8">
                  <div class="grid-content" style="margin-left:160px">json表达式/正则表达式</div>
                </el-col>
                <el-col :span="2">
                  <div class="grid-content" style="margin-left:40px">操作</div>
                </el-col>
              </el-row>
              <el-row v-for="(item,index) in responseList" :key="index">
                <el-col :span="5">
                  <el-input v-model.trim="item.paramsName" placeholder="请输入变量名称"></el-input>
                </el-col>
                <el-col :span="8">
                  <el-input v-model.trim="item.paramsValue" placeholder="请输入表达式" type="textarea" autosize></el-input>
                </el-col>
                <el-col :span="2">
                  <el-button size="mini" type="danger" @click="responeDel(index)" icon="el-icon-delete" style="height:40px;margin-left:20px">删除</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button type="primary" size="mini" plain @click="AddResponseListRow()" style="mragin-top:10px" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
          <!-- 断言 -->
          <el-collapse-item name="4" title="结果断言">
            <el-table :data="assertionList" border style="width:100%;margin-top: 15px;">
              <el-table-column label="Json表达式" width="350" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.check">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="比较符" width="250" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.comparator" placeholder="请选择">
                    <el-option v-for="item in selectAssertionList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="预期结果" width="350" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.expect">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="AssertionDelete(scope.$index)" style="height:40px">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" size="mini" plain @click="AddAssertionListRow()" style="mragin-top:10px" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
        </el-collapse>
        <div style="margin-left:800px;margin-top:20px">
          <el-button @click="cancelCaseFrom">取 消</el-button>
          <el-button type="primary" @click="addCaseFrom">确 定</el-button>
        </div>
      </el-card>
    </el-form>
  </div>
</template>
<script>
import { getModulList, interfaceDetailList } from '@/api/getAotoInterface'
import { getInterfaceDetail, addCase, editCase } from '@/api/getAutoCase'
export default {
  data() {
    return {
      queryModuleInfo: {
        pageNum: 1,
        pageSize: 10
      },
      moduleInfo: {
        pageNum: 1,
        pageSize: 100
      },
      interfaceInfo: {
        pageNum: 1,
        pageSize: 100,
        moduleId: ''
      },
      caseForm: {
        id: '',
        name: '',
        moduleId: '',
        moduleName: '',
        interfaceName: '',
        interfaceId: '',
        headers: '',
        parameters: '',
        extract: '',
        validate: ''
      },
      modelList: [],
      interfaceList: [],
      selectInterfacelId: '',
      rules: {
        moduleId: [
          {
            required: true,
            message: '模块名称不能为空！',
            trigger: 'blur'
          }
        ],
        interfaceId: [
          {
            required: true,
            message: '接口名称不能为空！',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '用例不能为空！',
            trigger: 'blur'
          }
        ]
      },
      isShow: false,
      activeNames: ['1', '2', '3', '4'],
      interfaceForm: {
        interfaceId: ''
      },
      assertionList: [],
      headersList: [],
      requestParamsList: [],
      responseList: [],
      selectAssertionList: [
        {
          id: 'eq',
          name: '等于'
        },
        {
          id: 'gt',
          name: '大于'
        },
        {
          id: 'lt',
          name: '小于'
        },
        {
          id: 'neq',
          name: '不等于'
        }
      ]
    }
  },
  created() {
    this.getModelList()
    this.$bus.$on('casemsg', (row) => {
      // console.log('接收到的信息', row)
      if (row !== null) {
        if (row === '新增') {
          this.isShow = false
          this.caseForm.name = ''
          this.caseForm.moduleId = ''
          this.caseForm.interfaceId = ''
          this.headersList = []
          this.requestParamsList = []
          this.responseList = []
          this.assertionList = []
        } else {
          // 编辑接收到的信息
          this.isShow = true
          this.caseForm.id = row.id
          this.caseForm.name = row.name
          this.caseForm.moduleId = row.moduleId
          this.caseForm.interfaceId = row.interfaceId
          this.caseForm.moduleName = row.moduleName
          this.caseForm.interfaceName = row.interfaceName
          // 请求头（将json字符串转化为对象）
          var newHeaders = JSON.parse(row.headers)
          this.headersList = []
          for (var i in newHeaders) {
            this.headersList.push({
              paramsName: i,
              paramsValue: newHeaders[i]
            })
          }
          // 请求参数
          var newParamters = JSON.parse(row.parameters)
          this.requestParamsList = []
          for (var j in newParamters) {
            this.requestParamsList.push({
              paramsName: j,
              paramsValue: newParamters[j]
            })
          }
          // 响应解析列表
          var newExtract = JSON.parse(row.extract)
          this.responseList = []
          for (var o in newExtract) {
            this.responseList.push({
              paramsName: o,
              paramsValue: newExtract[o]
            })
          }
          // 返回断言
          this.assertionList = JSON.parse(row.validate)
        }
      }
    })
  },
  methods: {
    // 获取模块列表
    getModelList() {
      getModulList(this.moduleInfo).then((resp) => {
        this.modelList = resp.data.data.list
      })
    },
    // 模块下拉框改变事件
    selectChangeModel(selectItem) {
      this.interfaceInfo.moduleId = selectItem
      interfaceDetailList(this.interfaceInfo).then((resp) => {
        this.interfaceList = resp.data.data.list
      })
    },
    // 接口下拉框改变事件
    selectChangeInterface() {
      this.isShow = true
      this.interfaceForm.interfaceId = this.caseForm.interfaceId
      // 获取接口详情
      getInterfaceDetail(this.interfaceForm).then((resp) => {
        this.headersList = JSON.parse(resp.data.data.headers)
        this.requestParamsList = JSON.parse(resp.data.data.paramTemplate)
        this.responseList = JSON.parse(resp.data.data.responseTemplate)
      })
    },
    // 添加Headers
    AddHeaderListRow() {
      this.headersList.push({
        paramsName: '',
        paramsValue: ''
      })
    },
    // 删除Headers
    advanceDelss(index) {
      this.headersList.splice(index, 1)
    },
    // 添加请求参数
    AddRequestParamsListRow() {
      this.requestParamsList.push({
        paramsName: '',
        paramsValue: ''
      })
    },
    // 删除请求参数
    requestParamsDel(index) {
      this.requestParamsList.splice(index, 1)
    },
    // 添加响应解析列表
    AddResponseListRow() {
      this.responseList.push({
        paramsName: '',
        paramsValue: ''
      })
    },
    // 删除响应解析信息
    responeDel(index) {
      this.responseList.splice(index, 1)
    },
    // 添加断言行
    AddAssertionListRow() {
      this.assertionList.push({
        check: '',
        comparator: '',
        expect: ''
      })
    },
    // 断言删除
    AssertionDelete(index) {
      this.assertionList.splice(index, 1)
    },
    // 添加case信息
    addCaseFrom() {
      // 将数组转化为对象
      var headersObj = {}
      this.headersList.forEach((item) => {
        headersObj[item.paramsName] = item.paramsValue
      })
      // 将对象转化为Json
      this.caseForm.headers = JSON.stringify(headersObj)
      // 请求参数
      var requestParamsObj = {}
      this.requestParamsList.forEach((item) => {
        requestParamsObj[item.paramsName] = item.paramsValue
      })
      this.caseForm.parameters = JSON.stringify(requestParamsObj)
      // 响应解析列表
      var responseObj = {}
      this.responseList.forEach((item) => {
        responseObj[item.paramsName] = item.paramsValue
      })
      this.caseForm.extract = JSON.stringify(responseObj)
      // 断言
      this.caseForm.validate = JSON.stringify(this.assertionList)
      // 输入框验证
      this.$refs.caseFormRef.validate((valid) => {
        if (!valid) {
          return false
        } else {
          if (this.caseForm.id) {
            // 编辑接口
            editCase(this.caseForm).then((resp) => {
              if (resp.data.data === true) {
                this.$message.success('修改成功！')
                this.$router.push('testcase')
                // 刷新列表页
                this.sendResh()
              } else {
                this.$message.error(resp.data.msg)
              }
            })
          } else {
            // 添加接口
            addCase(this.caseForm).then((resp) => {
              if (resp.data.data === true) {
                this.$message.success('添加成功！')
                // 返回列表页
                this.$router.push('testcase')
                // 刷新列表页
                this.sendResh()
              } else {
                this.$message.error(resp.data.msg)
              }
            })
          }
        }
      })
      console.log('保存信息', this.caseForm)
    },
    // 取消按钮
    cancelCaseFrom() {
      // 返回列表页
      this.$router.push('testcase')
    },
    // 刷新列表
    sendResh() {
      // bus使用
      this.$nextTick(function () {
        // DOM 现在更新了
        this.$bus.$emit('refresh')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.h-list {
  line-height: 20px;
  padding: 10px 0;
  font-size: 14px;
  color: #161b22;
  border-bottom: 1px solid #e9eaf1;
  div {
    padding-right: 5px;
    max-height: 150px;
    //overflow-y: auto;
    overflow-x: hidden;
    word-wrap: break-word;
  }
}
/deep/.el-textarea__inner {
  height: 40px !important;
  margin-left: 10px;
}

.el-input {
  margin: 0px 10px 5px 0px;
}
</style>
