<template>
  <div id="window-judge" style="background:#F2F3F6;min-height:95vh;">
    <el-container>
      <el-header style="background:#ffffff;height:auto; width:94%;margin:3%; font-size:14px;border-radius:8px;">
        <el-form ref="caseData" label-position="left" :model="caseData" label-width="80pt" style="margin:1%;" :rules="createFormData">
          <el-row>
            <el-col :span="21">
              <el-form-item label="用例名称" prop="title"><el-input v-model="caseData.title" placeholder="请填写【此处可能20字以上】…" /></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="21">
              <el-form-item label="前置条件"><el-input v-model="caseData.caseCondition" placeholder="请输入" /></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="21" style="white-space:nowrap; display:flex;">
              <el-form-item label="所属项目" style="flex:1"><el-input v-model="caseData.projectName" clearable placeholder="请输入" /></el-form-item>
              <el-form-item label="所属需求" style="flex:1; margin-left: 2%;"><el-input v-model="caseData.taskName" clearable placeholder="请输入" /></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="21" style="white-space:nowrap; display:flex;">
              <el-form-item label="用例优先级" style="flex:1">
                <el-select v-model="caseData.casePriority" clearable placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in priorityStrings" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="API" style="flex:1; margin-left: 2%;"><el-input v-model="caseData.api" clearable placeholder="请输入" /></el-form-item>
            </el-col>
          </el-row>
          <!-- http://star.xiaojukeji.com/upload/img.node -->
          <el-row>
            <el-col :span="21" style="display:flex;" class="upload">
              <el-form-item label="附件" style="flex:1">
                <el-upload v-model="caseData.accessory" class="upload-demo" drag action="https://jsonplaceholder.typicode.com/posts/" multiple :on-success="handleAvatarSuccess" :on-progress="DisableButton">
                  <i class="el-icon-plus avatar-uploader-icon"> 添加图片 </i>
                </el-upload>
              </el-form-item>
              <el-form-item label="备注" style="flex:1; margin-left: 2%;">
                <el-input v-model="caseData.remark" type="textarea" :rows="8" placeholder="请填写..." />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-show="btn_show" align="center" class="cla">
          <el-table v-show="btn_show" :data="uptataKey" fit style="width: 90%;">
            <el-table-column label="" min-width="150">
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column label="" min-width="300">
              <template slot-scope="scope"><a :href="scope.row.url" style="color:blue;">{{ scope.row.url }}</a></template>
            </el-table-column>
            <el-table-column fixed="right" label="" width="50" align="center">
              <template slot-scope="scope">
                <el-button class="deleteSty" @click="deleteURL(scope.row)"> x </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-header>
      <el-main style="background:#ffffff;height:auto; width:94%;margin: 0 3% 3% 3%; font-size:14px;border-radius:8px;">
        <!-- 新增 -->
        <el-form v-for="(item, index) in data" :key="index" label-width="100px" :model="item">
          <div style="display:flex; white-space:nowrap;">
            <el-form-item label="执行步骤" style="flex:1"><el-input v-model="item.description" placeholder="请填写【此处可能20字以上】…" /></el-form-item>
            <el-form-item label="预期结果" style="flex:1"><el-input v-model="item.expectedResult" placeholder="请填写" /></el-form-item>
            <div style="flex:0.1; margin:0.26% 3%;">
              <el-button size="mini" type="primary" icon="el-icon-plus" @click="add" />
              <el-button size="mini" icon="el-icon-minus" @click="deleteData(index)" />
            </div>
          </div>
        </el-form>
        <el-row>
          <el-col :span="22" style="text-align:right; ">
            <el-button :disabled="dis" type="primary" @click=" title_Name === '新增' ? caseCreateCase(caseData) : caseQueryCase(caseData)">保 存</el-button>
            <el-button style="margin:9% 0 0 4%;" @click="$router.go(-1)">取 消</el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { createCaseData, queryCasesData, updateCaseData } from '@/api/caseProject.js'

export default {
  data() {
    return {
      data: [{ description: '', expectedResult: '' }],
      userNames: localStorage.getItem('username'),
      bizJson: localStorage.getItem('key'),
      startId: '',
      caseData: {},
      dis: false,
      btn_show: false,
      id: '',
      arr: [],
      uptataKey: [],
      title_Name: '',
      createFormData: { title: [{ required: true, message: '用例名称不能为空', trigger: 'change' }] },
      priorityStrings: [{ name: 'p0', value: 0 }, { name: 'p1', value: 1 }, { name: 'p2', value: 2 }, { name: 'p3', value: 3 }]
    }
  },
  created() {
    this.initCode()
  },
  methods: {
    // 初始化
    initCode() {
      if (this.$route.query.data) {
        this.title_Name = '新增'
        this.$set(this.caseData, 'casePriority', 3)
        this.startId = this.$route.query.data
        if (this.$refs['caseData'] !== undefined) {
          this.$refs['caseData'].resetFields()
        }
      }
      if (this.$route.query.id) {
        this.title_Name = '编辑'
        this.url = window.location.href // 获取url中"?"符后的字串
        this.caseFolderId = this.url.split('&caseFolderId=')
        this.id = this.caseFolderId[0].split('?id=')
        queryCasesData({ caseFolderId: this.caseFolderId[1] }).then(res => {
          for (var el of res.data.list) {
            if (el.id === Number(this.id[1])) {
              this.caseData = el
              if (this.caseData.description !== '') {
                var obj_description = JSON.parse(this.caseData.description.split('{}'))
                this.data = obj_description
              }
              if (this.caseData.accessory !== '') {
                this.btn_show = true
                var obj = JSON.parse(this.caseData.accessory.split('{}'))
                for (var a of obj) {
                  this.uptataKey.push(a)
                }
                break
              }
            }
          }
        })
      }
    },

    // 图片上传成功的回调
    handleAvatarSuccess(response, file, fileList) {
      this.arr.push({ name: file.name, url: 'http:' + file.response.url })
      this.dis = false
    },

    // 上传成功可以提交
    DisableButton() {
      this.dis = true
    },

    // 添加事件
    add() {
      this.data.push({ description: '', expectedResult: '' })
    },

    // 删除事件
    deleteData(e) {
      this.data.splice(e, 1)
    },

    // 图片上传成功的回调(编辑)
    constractSuccUpload(response, file, fileList) {
      this.dis = false
      const fileUrl = { name: file.name, url: 'http:' + file.response.url }
      this.uptataKey.push(fileUrl)
    },

    // 删除附件（编辑）
    deleteURL(vel) {
      for (var i = 0; i < this.uptataKey.length; i++) {
        if (this.uptataKey[i].name === vel.name) {
          this.uptataKey.splice(i, 1)
        }
      }
    },

    // 编辑_数据
    caseQueryCase(vel) {
      this.caseData = vel
      this.caseData.description = JSON.stringify(this.data)
      this.caseData.accessory = JSON.stringify(this.arr)
      updateCaseData(this.caseData).then(res => {
        this.$message({ type: 'success', message: res.msg, duration: 1000 })
        this.$router.go('-1')
      })
    },

    // 新建Data
    caseCreateCase(vel) {
      this.$refs['caseData'].validate((valid) => {
        if (valid) {
          this.caseData = vel
          this.caseData.accessory = JSON.stringify(this.arr)
          this.caseData.description = JSON.stringify(this.data)
          this.caseData.creator = this.userNames
          this.caseData.modifier = this.userNames
          this.caseData.caseFolderId = this.startId
          this.caseData.bizId = this.bizJson
          createCaseData(this.caseData).then(res => {
            if (res.code === 200) {
              this.$message({ type: 'success', message: res.msg, duration: 1000 })
              this.$router.go('-1')
            } else {
              this.$message({ type: 'error', message: res.msg, duration: 1000 })
            }
          })
        }
      })
    }
  }
}
</script>

<style>
.bgColorSz {
  width: 100%;
  height: 96vh;
  background: #F2F3F6;
  font-size: 0.9rem;
  display: flex;
  justify-content: center;
  align-items: center;
  }

.cla .el-table td {
  padding:0px;
}
.deleteSty {
  cursor: pointer;
  border: none;
}
.upload .avatar-uploader-icon {
  font-size: 14px;
  color: #8c939d;
  line-height: 178px;
  text-align: center;
}
</style>
