<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="6">
                  <div class="grid-content" style="margin-left:15px">参数名称</div>
                </el-col>
                <el-col :span="10">
                  <div class="grid-content" style="margin-left:15px">参数值</div>
                </el-col>
                <el-col :span="2">
                  <div class="grid-content" style="margin-left:25px">操作</div>
                </el-col>
              </el-row>
              <el-row v-for="(item,index) in headersList" :key="index">
                <el-col :span="6">
                  <div style="margin-top:10px">
                    <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                  </div>
                </el-col>
                <el-col :span="10">
                  <div style="margin-left:5px;">
                    <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值" type="textarea"></el-input>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div style="margin-top:6px">
                    <el-button size="mini" type="danger" @click="advanceDelss(index)" icon="el-icon-delete" style="height:40px;margin-left:20px">删除</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button type="success" 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="6">
                  <div class="grid-content" style="margin-left:15px">参数名称</div>
                </el-col>
                <el-col :span="10">
                  <div class="grid-content" style="margin-left:15px">参数值</div>
                </el-col>
                <el-col :span="2">
                  <div class="grid-content" style="margin-left:25px">操作</div>
                </el-col>
              </el-row>
              <el-row v-for="(item,index) in requestParamsList" :key="index">
                <el-col :span="6">
                  <div style="margin-top:10px">
                    <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                  </div>
                </el-col>
                <el-col :span="10">
                  <div style="margin-left:5px">
                    <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值" type="textarea"></el-input>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div style="margin-top:6px">
                    <el-button size="mini" type="danger" @click="requestParamsDel(index)" icon="el-icon-delete" style="height:40px;margin-left:20px">删除</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button type="success" 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="6">
                  <div class="grid-content" style="margin-left:15px">参数名称</div>
                </el-col>
                <el-col :span="10">
                  <div class="grid-content" style="margin-left:15px">参数值</div>
                </el-col>
                <el-col :span="2">
                  <div class="grid-content" style="margin-left:25px">操作</div>
                </el-col>
              </el-row>
              <el-row v-for="(item,index) in paramsList" :key="index">
                <el-col :span="6">
                  <div style="margin-top:10px">
                    <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                  </div>
                </el-col>
                <el-col :span="10">
                  <div style="margin-left:5px">
                    <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值" type="textarea"></el-input>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div style="margin-top:6px">
                    <el-button size="mini" type="danger" @click="paramsDel(index)" icon="el-icon-delete" style="height:40px;margin-left:20px">删除</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button type="success" plain @click="AddParamsListRow()" style="mragin-top:10px" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
          <!-- 响应解析列表 -->
          <el-collapse-item name="4" title="响应提取">
            <el-form-item>
              <el-row>
                <el-col :span="6">
                  <div class="grid-content" style="margin-left:15px">变量名称</div>
                </el-col>
                <el-col :span="10">
                  <div class="grid-content" style="margin-left:15px">json路径表达式</div>
                </el-col>
                <el-col :span="2">
                  <div class="grid-content" style="margin-left:25px">操作</div>
                </el-col>
              </el-row>
              <el-row v-for="(item,index) in responseList" :key="index">
                <el-col :span="6">
                  <div style="margin-top:10px">
                    <el-input v-model.trim="item.paramsName" placeholder="请输入变量名称"></el-input>
                  </div>
                </el-col>
                <el-col :span="10">
                  <div style="margin-left:5px">
                    <el-input v-model.trim="item.paramsValue" placeholder="请输入表达式" type="textarea"></el-input>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div style="margin-top:6px">
                    <el-button size="mini" type="danger" @click="responeDel(index)" icon="el-icon-delete" style="height:40px;margin-left:20px">删除</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button type="success" plain @click="AddResponseListRow()" style="mragin-top:10px" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
          <!-- 断言 -->
          <el-collapse-item name="5" title="结果断言">
            <el-table :data="assertionList" border style="width:100%;margin-top: 15px;">
              <el-table-column label="表达式" width="350">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.check">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="断言" width="250">
                <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">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.expect">
                  </el-input>
                </template>
              </el-table-column>
              <!-- <el-table-column label="是否必填" width="150" style="text-align:center">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.isRequired" active-color="#13ce66" inactive-color="#A9A9A9" active-text="是" inactive-text="否" @change="changeState()"></el-switch>
                </template>
              </el-table-column> -->
              <!-- <el-table-column label="示例" width="300">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.examples"></el-input>
                </template>
              </el-table-column> -->
              <!-- <el-table-column label="备注" width="250">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remarks"></el-input>
                </template>
              </el-table-column> -->
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="AssertionDelete(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="success" plain @click="AddAssertionListRow()" style="mragin-top:10px" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
        </el-collapse>
        <div style="margin-left:700px;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'
// import bus from '@/utils/bus'
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: '',
        variables: '',
        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',
      interfaceForm: {
        interfaceId: ''
      },
      assertionList: [],
      headersList: [],
      requestParamsList: [],
      paramsList: [],
      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.paramsList = []
          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 newVariables = JSON.parse(row.variables)
          this.paramsList = []
          for (var k in newVariables) {
            this.paramsList.push({
              paramsName: k,
              paramsValue: newVariables[k]
            })
          }
          // 响应解析列表
          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) {
      console.log(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)
    },
    // 参数列表
    AddParamsListRow() {
      this.paramsList.push({
        paramsName: '',
        paramsValue: ''
      })
    },
    // 参数列表删除
    paramsDel(index) {
      this.paramsList.splice(index, 1)
    },
    // 添加响应解析列表
    AddResponseListRow() {
      this.responseList.push({
        paramsName: '',
        paramsValue: ''
      })
    },
    // 删除响应解析信息
    responeDel(index) {
      this.responseList.splice(index, 1)
    },
    // 添加断言行
    AddAssertionListRow() {
      this.assertionList.push({
        check: '',
        comparator: '',
        expect: ''
      })
    },
    // 断言改变
    // changeState(e) {
    //   if (e === true) {
    //     this.assertionList.isRequired = e
    //   } else {
    //     this.assertionList.isRequired = e
    //   }
    // },
    // 断言删除
    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 paramsListObj = {}
      this.paramsList.forEach((item) => {
        paramsListObj[item.paramsName] = item.paramsValue
      })
      this.caseForm.variables = JSON.stringify(paramsListObj)
      // 响应解析列表
      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('CaseList')
                // 刷新列表页
                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('CaseList')
                // 刷新列表页
                this.sendResh()
              } else {
                this.$message.error(resp.data.msg)
              }
            })
          }
        }
      })
    },
    // 取消按钮
    cancelCaseFrom() {
      // 返回列表页
      this.$router.push('CaseList')
    },
    // 刷新列表
    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;
  }
}
</style>
