<template>
  <div>
    <el-form ref="sceneForm" :rules="rules" :model="sceneForm" label-width="90px">
      <el-form-item label="场景名称:" prop="name" style="width:300px">
        <el-input v-model="sceneForm.name"></el-input>
      </el-form-item>
      <el-form-item label="项目名称:" prop="projectId">
        <el-select v-model="sceneForm.projectId" placeholder="请选择项目" clearable>
          <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-button type="success" plain @click="DialogVisible = true" class="el-icon-circle-plus">添加</el-button>

        <el-table :data="sceneTestcaseList" border style="width: 100%;margin-top:20px" row-key="sequence">
          <!-- <el-table-column prop='sequence' width="50px"></el-table-column> -->
          <!-- <el-table-column type='index' width="50px"></el-table-column> -->
          <!-- <el-table-column prop="moduleName" label="模块名称" width="200px"></el-table-column>
          <el-table-column prop="interfaceName" label="接口名称" width="200px"></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="success" @click="editeSceneFrom(scope.row)">编辑</el-button>
              <el-button type="danger" @click="deleSceneFrom(scope.row)">删除</el-button>
            </slot>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <div style="margin-top:20px;float:right;margin-right:500px">
          <el-button type="primary" @click="addSceneCaseFrom">确 定</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 添加场景用例 -->
    <el-dialog title="新增场景用例" :visible.sync="DialogVisible" width="30%">
      <el-form :model="sceneCaseForm" label-width="90px">
        <el-form-item label="模块名称:" 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="接口名称:" 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="DialogVisible = false">取 消</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="caseForm.name" :disabled="true"></el-input>
          </el-form-item> -->
          <el-collapse v-model="activeNames">
            <!-- Headers -->
            <el-collapse-item name="1" title="请求头">
              <el-button type="success" plain @click="AddHeaderListRow()" class="el-icon-circle-plus">添加行</el-button>
              <el-form-item>
                <el-row>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数名称</div>
                  </el-col>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数值</div>
                  </el-col>
                  <el-col :span="6">
                    <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>
                      <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-button size="mini" type="danger" @click="advanceDelss(index)" style="height:40px;margin-left:20px">删除</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-collapse-item>
            <!-- 请求参数 -->
            <el-collapse-item name="2" title="请求参数">
              <el-button type="success" plain @click="AddRequestParamsListRow()" class="el-icon-circle-plus">添加行</el-button>
              <el-form-item>
                <el-row>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数名称</div>
                  </el-col>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数值</div>
                  </el-col>
                  <el-col :span="6">
                    <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>
                      <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-button size="mini" type="danger" @click="requestParamsDel(index)" style="height:40px;margin-left:20px">删除</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-collapse-item>
            <!-- 参数列表 -->
            <el-collapse-item name="3" title="参数列表">
              <el-button type="success" plain @click="AddParamsListRow()" class="el-icon-circle-plus">添加行</el-button>
              <el-form-item>
                <el-row>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数名称</div>
                  </el-col>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数值</div>
                  </el-col>
                  <el-col :span="6">
                    <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>
                      <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-button size="mini" type="danger" @click="paramsDel(index)" style="height:40px;margin-left:20px">删除</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-collapse-item>
            <!-- 响应解析列表 -->
            <el-collapse-item name="4" title="响应列表">
              <el-button type="success" plain @click="AddResponseListRow()" class="el-icon-circle-plus">添加行</el-button>
              <el-form-item>
                <el-row>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数名称</div>
                  </el-col>
                  <el-col :span="6">
                    <div class="grid-content" style="margin-left:15px">参数值</div>
                  </el-col>
                  <el-col :span="6">
                    <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>
                      <el-input v-model.trim="item.paramsName" placeholder="请输入参数名称"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-input v-model.trim="item.paramsValue" placeholder="请输入参数值"></el-input>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div>
                      <el-button size="mini" type="danger" @click="responeDel(index)" style="height:40px;margin-left:20px">删除</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-collapse-item>
            <!-- 断言 -->
            <el-collapse-item name="5" title="结果断言">
              <el-button type="success" plain @click="AddAssertionListRow()" class="el-icon-circle-plus">添加行</el-button>
              <el-table :data="assertionList" border style="width:100%;margin-top: 15px;">
                <el-table-column label="参数名称" width="150">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.paramsName">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="参数值" width="150">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.paramsValue">
                    </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="300">
                  <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" @click="AssertionDelete(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </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: 'moduleName' },
        { label: '接口名称', prop: 'interfaceName' }
      ],
      queryProjectList: {
        pageNum: 1,
        pageSize: 20
      },
      sceneForm: {
        name: '',
        projectId: ''
      },
      projectList: [],
      rules: {
        name: [
          {
            required: true,
            message: '场景名称不能为空！',
            trigger: 'blur'
          }
        ],
        projectId: [
          {
            required: true,
            message: '项目名称不能为空！',
            trigger: 'blur'
          }
        ]
      },
      sceneCaseForm: {
        caseDetialList: [],
        moduleName: '',
        moduleId: '',
        interfaceName: '',
        interfaceId: '',
        caseList: [],
        moduleFrom: {
          id: '',
          name: ''
        },
        interfaceFrom: {
          id: '',
          name: ''
        },
        sequence: 0,
        caseId: '',
        caseName: '',
        headers: '',
        parameters: '',
        variables: '',
        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',
      headersList: [],
      requestParamsList: [],
      paramsList: [],
      responseList: [],
      assertionList: [],
      caseForm: {
        sceneId: '',
        interfaceId: '',
        name: '',
        headers: '',
        parameters: '',
        variables: '',
        extract: '',
        validate: '',
        sequence: '',
        caseId: '',
        newInterfaceId: ''
      },
      newIndex: 0,
      newCaseIndex: 0,
      newSceneForm: {
        sceneId: '',
        sceneTestcaseList: []
      }
    }
  },
  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 }) {
          // console.log('索引新', newIndex)
          // console.log('索引旧', 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,
        name: this.sceneCaseForm.caseDetialList[0].name,
        headers: this.sceneCaseForm.caseDetialList[0].headers,
        parameters: this.sceneCaseForm.caseDetialList[0].parameters,
        variables: this.sceneCaseForm.caseDetialList[0].variables,
        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 = []
    },
    // 编辑场景用例
    editeSceneFrom(row) {
      console.log('11', row)
      this.editDialogVisible = true
      this.sceneCaseForm.sequence = row.sequence
      this.sceneCaseForm.interfaceId = row.interfaceId
      this.sceneCaseForm.caseId = row.id
      this.sceneCaseForm.caseName = 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 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)
    },
    // 保存场景用例方法
    addSceneCaseFrom() {
      var index = 1
      this.sceneTestcaseList.forEach((item) => {
        item.sequence = index
        index += 1
      })
      this.newSceneForm.sceneId = this.sceneCaseInfo.sceneId
      this.newSceneForm.sceneTestcaseList = this.sceneTestcaseList
      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)
        }
      })
    },
    // 刷新列表
    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)
    },
    // 天机参数列表行
    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({
        paramsName: '',
        paramsValue: '',
        isRequired: true,
        examples: '',
        remarks: ''
      })
    },
    // 断言改变
    changeState(e) {
      if (e === true) {
        this.assertionList.isRequired = e
      } else {
        this.assertionList.isRequired = e
      }
    },
    // 删除断言行
    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 paramsListObj = {}
      this.paramsList.forEach((item) => {
        paramsListObj[item.paramsName] = item.paramsValue
      })
      this.sceneCaseForm.variables = JSON.stringify(paramsListObj)
      // 响应解析列表
      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
      //   ) {
      //     var moduleName = this.sceneTestcaseList[i].moduleName
      //     var interfaceName = this.sceneTestcaseList[i].interfaceName
      //     this.sceneTestcaseList.splice(i, 1)
      //   }
      // }
      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].variables = this.sceneCaseForm.variables
          this.sceneTestcaseList[i].extract = this.sceneCaseForm.extract
          this.sceneTestcaseList[i].validate = this.sceneCaseForm.validate
        }
      }
      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>
