<template>
  <div>
    <el-form ref="sceneFormRef" :rules="rules" :model="sceneForm" label-width="90px">
      <el-form-item label="场景名称:" prop="name" style="width:310px">
        <el-input v-model="sceneForm.name" disabled></el-input>
      </el-form-item>
      <el-form-item label="项目名称:" prop="projectId">
        <el-select v-model="sceneForm.projectId" disabled>
          <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- 列表展示 -->
        <el-table :data="sceneTestcaseList" border style="width: 100%;margin-top:20px;cursor:pointer" row-key="sequence">
          <el-table-column prop='sequence' label="序号" width="60px" align="center"></el-table-column>
          <el-table-column v-for="(item, index) in col" :key="`col_${index}`" :prop="col[index].prop" :label="item.label" align="center"></el-table-column>
          <el-table-column label="操作">
            <slot slot-scope="scope">
              <el-button type="warning" icon="el-icon-edit" @click="editeSceneFrom(scope.row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" @click="deleSceneFrom(scope.row)">删除</el-button>
            </slot>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="success" plain @click="DialogVisible = true" class="el-icon-circle-plus">添加</el-button>
        <div style="margin-top:20px;float:right;margin-right:300px">
          <el-button @click="cancelSceneCaseFrom">取 消</el-button>
          <el-button type="primary" @click="addSceneCaseFrom">确 定</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 添加场景用例 -->
    <el-dialog title="新增场景用例" :visible.sync="DialogVisible" width="50%">
      <el-form ref="sceneCaseFormRef" :rules="rules" :model="sceneCaseForm" label-width="90px">
        <el-form-item label="模块名称:" prop="moduleName" style="width:300px">
          <el-select v-model="sceneCaseForm.moduleFrom" value-key="id" placeholder="请选择模块" @change="selectChangeModel" clearable>
            <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口名称:" prop="interfaceName" style="width:500px">
          <el-select v-model="sceneCaseForm.interfaceFrom" value-key="id" placeholder="请选择接口" @change="selectChangeInterface" clearable>
            <el-option v-for="item in interfaceList" :key="item.id" :label="item.name" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-table :data="sceneCaseForm.caseList" border style="width: 100%;margin-left:1px" @selection-change="handleSelectionChange">
            <el-table-column type="selection" style="width:10%">
            </el-table-column>
            <el-table-column type='index' style="width:15%"></el-table-column>
            <el-table-column prop="name" label="用例名称" style="width:60%"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="canceSceneFrom">取 消</el-button>
        <el-button type="primary" @click="addSceneFrom">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑场景用例 -->
    <el-dialog title="编辑场景用例" :visible.sync="editDialogVisible" width="60%">
      <!-- <el-card> -->
      <el-form>
        <el-form-item label="用例名称:" style="width:310px;">
          <el-input v-model="sceneCaseForm.name"></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 class="div-top">
                    <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                  </div>
                </el-col>
                <el-col :span="10">
                  <div class="div-left">
                    <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值" type="textarea" autosize></el-input>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div class="div-operation">
                    <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()" 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 class="div-top">
                    <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                  </div>
                </el-col>
                <el-col :span="10">
                  <div class="div-left">
                    <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值" type="textarea" autosize></el-input>
                  </div>
                </el-col>
                <el-col :span="2">
                  <div class="div-operation">
                    <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()" 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">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 class="div-top">
                    <el-input v-model.trim="item.paramsName" placeholder="请输入变量名称"></el-input>
                  </div>
                </el-col>
                <el-col :span="10">
                  <div class="div-left">
                    <el-input v-model.trim="item.paramsValue" placeholder="请输入表达式" type="textarea" autosize></el-input>
                  </div>
                </el-col>
                <el-col :span="2">autosize
                  <div class="div-operation">
                    <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()" 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">
                <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="操作">
                <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()" class="el-icon-circle-plus">添加行</el-button>
          </el-collapse-item>
        </el-collapse>
        <div style="margin-top:20px;margin-left:400px">
          <el-button @click="cancelCaseFrom">取 消</el-button>
          <el-button type="primary" @click="addCaseFrom">确 定</el-button>
        </div>
      </el-form>
      <!-- </el-card> -->
    </el-dialog>
  </div>
</template>
<script>
import {
  getProjectList,
  getModulList,
  interfaceDetailList,
  getCaseByInterface
} from '@/api/getAotoInterface'
import { getSceneCaseList, addSceneCase } from '@/api/getAutoScene'
import Sortable from 'sortablejs'
export default {
  data() {
    return {
      col: [
        { label: '用例名称', prop: 'name' },
        { label: '接口Url', prop: 'interfaceUrl' },
        { label: '模块名称', prop: 'moduleName' }
      ],
      queryProjectList: {
        pageNum: 1,
        pageSize: 20
      },
      sceneForm: {
        name: '',
        projectId: ''
      },
      projectList: [],
      rules: {
        name: [
          {
            required: true,
            message: '场景名称不能为空！',
            trigger: 'blur'
          }
        ],
        projectId: [
          {
            required: true,
            message: '项目名称不能为空！',
            trigger: 'blur'
          }
        ],
        moduleName: [
          {
            required: true,
            message: '模块名称不能为空！',
            trigger: 'blur'
          }
        ],
        interfaceName: [
          {
            required: true,
            message: '接口名称不能为空！',
            trigger: 'blur'
          }
        ],
        caseName: [
          {
            required: true,
            message: '用例名称不能为空！',
            trigger: 'blur'
          }
        ]
      },
      sceneCaseForm: {
        caseDetialList: [],
        moduleName: '',
        moduleId: '',
        interfaceName: '',
        interfaceId: '',
        caseList: [],
        moduleFrom: {
          id: '',
          name: ''
        },
        interfaceFrom: {
          id: '',
          name: ''
        },
        sequence: 0,
        caseId: '',
        name: '',
        headers: '',
        parameters: '',
        extract: '',
        validate: '',
        sceneId: ''
      },
      sceneTestcaseList: [],
      sceneCaseInfo: {
        sceneId: ''
      },
      DialogVisible: false,
      modelList: [],
      interfaceList: [],
      moduleInfo: {
        pageNum: 1,
        pageSize: 100
      },
      interfaceInfo: {
        pageNum: 1,
        pageSize: 100,
        moduleId: ''
      },
      caseInfo: {
        interfaceId: ''
      },
      editDialogVisible: false,
      activeNames: ['1', '2', '3', '4'],
      headersList: [],
      requestParamsList: [],
      responseList: [],
      assertionList: [],
      caseForm: {
        sceneId: '',
        interfaceId: '',
        name: '',
        headers: '',
        parameters: '',
        extract: '',
        validate: '',
        sequence: '',
        caseId: '',
        newInterfaceId: ''
      },
      newIndex: 0,
      newCaseIndex: 0,
      newSceneForm: {
        sceneId: '',
        sceneTestcaseList: []
      },
      selectAssertionList: [
        {
          id: 'eq',
          name: '等于'
        },
        {
          id: 'gt',
          name: '大于'
        },
        {
          id: 'lt',
          name: '小于'
        },
        {
          id: 'neq',
          name: '不等于'
        }
      ]
    }
  },
  created() {
    this.getProjectList()
    this.getModelList()
    this.$bus.$off('scenemsg').$on('scenemsg', (row) => {
      // console.log('参数信息', row)
      this.sceneForm.name = row.name
      this.sceneForm.projectId = row.projectId
      this.sceneCaseInfo.sceneId = row.id
      this.getSceneCaseList()
      this.rowDrop()
    })
  },
  mounted() {
    this.rowDrop()
  },
  methods: {
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        draggable: '.el-table__row',
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.sceneTestcaseList.splice(oldIndex, 1)[0]
          _this.sceneTestcaseList.splice(newIndex, 0, currRow)
        }
      })
    },
    // 获取项目列表
    getProjectList() {
      getProjectList(this.queryProjectList).then((resp) => {
        this.projectList = resp.data.data.list
      })
    },
    // 获取场景用例列表
    getSceneCaseList() {
      getSceneCaseList(this.sceneCaseInfo).then((resp) => {
        this.sceneTestcaseList = resp.data.data
      })
    },
    // 获取模块列表
    getModelList() {
      getModulList(this.moduleInfo).then((resp) => {
        this.modelList = resp.data.data.list
      })
    },
    // 模块下拉框改变事件
    selectChangeModel() {
      this.interfaceInfo.moduleId = this.sceneCaseForm.moduleFrom.id
      interfaceDetailList(this.interfaceInfo).then((resp) => {
        this.interfaceList = resp.data.data.list
      })
    },
    // 选择接口下拉框改变事件
    selectChangeInterface() {
      this.caseInfo.interfaceId = this.sceneCaseForm.interfaceFrom.id
      getCaseByInterface(this.caseInfo).then((resp) => {
        this.sceneCaseForm.caseList = resp.data.data
      })
    },
    // 选择事件
    handleSelectionChange(row) {
      this.sceneCaseForm.caseDetialList = row
    },
    // 添加确定按钮
    addSceneFrom() {
      this.sceneTestcaseList.push({
        moduleName: this.sceneCaseForm.moduleFrom.name,
        interfaceName: this.sceneCaseForm.interfaceFrom.name,
        interfaceUrl: this.sceneCaseForm.caseDetialList[0].interfaceUrl,
        name: this.sceneCaseForm.caseDetialList[0].name,
        headers: this.sceneCaseForm.caseDetialList[0].headers,
        parameters: this.sceneCaseForm.caseDetialList[0].parameters,
        extract: this.sceneCaseForm.caseDetialList[0].extract,
        validate: this.sceneCaseForm.caseDetialList[0].validate,
        id: this.sceneCaseForm.caseDetialList[0].id,
        interfaceId: this.sceneCaseForm.caseDetialList[0].interfaceId,
        sceneId: this.sceneCaseInfo.sceneId,
        sequence: this.sceneTestcaseList.length + 1
      })
      console.log('save----', this.sceneTestcaseList)
      this.DialogVisible = false
      this.sceneCaseForm.moduleFrom = ''
      this.sceneCaseForm.interfaceFrom = ''
      this.sceneCaseForm.caseList = []
    },
    // 取消按钮
    canceSceneFrom() {
      this.DialogVisible = false
      this.sceneCaseForm.moduleFrom = ''
      this.sceneCaseForm.interfaceFrom = ''
      this.sceneCaseForm.caseList = []
    },

    // 编辑场景用例
    editeSceneFrom(row) {
      this.editDialogVisible = true
      this.sceneCaseForm.sequence = row.sequence
      this.sceneCaseForm.interfaceId = row.interfaceId
      this.sceneCaseForm.caseId = row.id
      this.sceneCaseForm.name = row.name
      var newHeaders = JSON.parse(row.headers)
      // 请求头（将json字符串转化为对象）
      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)
    },
    // 保存场景用例方法
    addSceneCaseFrom() {
      var index = 1
      this.sceneTestcaseList.forEach((item) => {
        item.sequence = index
        index += 1
      })
      this.newSceneForm.sceneId = this.sceneCaseInfo.sceneId
      this.newSceneForm.sceneTestcaseList = this.sceneTestcaseList
      console.log('保存传递的参数值', this.newSceneForm.sceneTestcaseList)
      this.$refs.sceneFormRef.validate((valid) => {
        if (!valid) {
          return false
        } else {
          addSceneCase(this.newSceneForm).then((resp) => {
            if (resp.data.data === true) {
              this.$message.success('保存成功！')
              // 返回列表页
              this.$router.push({ path: 'SceneList' })
              // 刷新列表页
              this.sendResh()
            } else {
              this.$message.error(resp.data.msg)
            }
          })
        }
      })
    },
    // 取消按钮事件
    cancelSceneCaseFrom() {
      // 返回列表页
      this.$router.push({ path: 'SceneList' })
    },
    // 刷新列表
    sendResh() {
      // bus使用
      this.$nextTick(function () {
        // DOM 现在更新了
        this.$bus.$emit('refreshScene')
      })
    },
    // 添加Header行
    AddHeaderListRow() {
      this.headersList.push({
        paramsName: '',
        paramsValue: ''
      })
    },
    // 删除Header行
    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)
    },
    // 修改确定按钮
    addCaseFrom() {
      // 将数组重新赋值（将数组转化为对象）
      var headersObj = {}
      this.headersList.forEach((item) => {
        headersObj[item.paramsName] = item.paramsValue
      })
      // 将对象转化为Json
      this.sceneCaseForm.headers = JSON.stringify(headersObj)
      // 请求参数
      var requestParamsObj = {}
      this.requestParamsList.forEach((item) => {
        requestParamsObj[item.paramsName] = item.paramsValue
      })
      this.sceneCaseForm.parameters = JSON.stringify(requestParamsObj)
      // 响应解析列表
      var responseObj = {}
      this.responseList.forEach((item) => {
        responseObj[item.paramsName] = item.paramsValue
      })
      this.sceneCaseForm.extract = JSON.stringify(responseObj)
      // 断言
      this.sceneCaseForm.validate = JSON.stringify(this.assertionList)
      // 循环数组并删除对应的数组下标的整条数据信息
      for (var i = 0; i < this.sceneTestcaseList.length; i++) {
        if (
          this.sceneTestcaseList[i].sequence === this.sceneCaseForm.sequence
        ) {
          this.sceneTestcaseList[i].headers = this.sceneCaseForm.headers
          this.sceneTestcaseList[i].parameters = this.sceneCaseForm.parameters
          this.sceneTestcaseList[i].extract = this.sceneCaseForm.extract
          this.sceneTestcaseList[i].validate = this.sceneCaseForm.validate
          this.sceneTestcaseList[i].name = this.sceneCaseForm.name
        }
      }
      this.editDialogVisible = false
      console.log('新集合信息', this.sceneTestcaseList)
    },
    cancelCaseFrom() {
      this.editDialogVisible = false
    },
    // 删除场景用例
    deleSceneFrom(row) {
      for (var i = 0; i < this.sceneTestcaseList.length; i++) {
        if (this.sceneTestcaseList[i].id === row.id) {
          this.sceneTestcaseList.splice(i, 1)
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-select {
  width: 220px;
}
.input {
  width: 300px;
}
.div-top {
  margin-top: 5px;
}
.div-left {
  margin-left: 5px;
  // margin-top:10px
}
.div-operation {
  // margin-top: 6px;
}
</style>
