<template>
  <div v-loading="loading">
    <div style="margin-bottom:20px;" v-if="isVisible">
      <el-dropdown trigger="click" @command="handleAdd">
        <el-button type="primary" plain icon="el-icon-plus" size="mini">添加步骤</el-button>
        <el-button type="primary" plain icon="el-icon-caret-right" size="mini" :disabled="isVisible">调试</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="dict in dict.type.step_type" :command="dict.value" :key="dict.value">{{ dict.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div style="margin-bottom:20px;" v-if="!isVisible">
      <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="caseEditVisible">用例编排</el-button>
      <el-button type="primary" plain icon="el-icon-caret-right" size="mini" @click="handleRun(id)">调试</el-button>
    </div>
    <div>
    </div>
    <el-collapse v-model="activeName" accordion v-if="list && list.length">
      <draggable v-model="list" @end="onDragEnd" handle=".drag-handle">
      <el-collapse-item :name="index" v-for="(item, index) in list" :key="index" v-if="!item.parentId">
        <template slot="title">
          <el-button size="mini" plain type="warning" icon="el-icon-rank" circle style="margin-right: 12px" class="drag-handle"/>
          <el-tag effect="plain" style="width: 70px;text-align: center;margin-right: 12px;" class="drag-handle">{{ dict.type.step_type.findLast(t => t.value == item.type).label }}</el-tag>
          <el-tag v-if="item.name" effect="plain" style="width: 240px;text-align: center;margin-right: 12px;" type="info" class="drag-handle">{{ item.name }}</el-tag>
          <el-tag v-if="item.datasourceId && item.type < 3" effect="plain" style="width: 240px;text-align: center;margin-right: 12px;" type="info" class="drag-handle">{{ datasourceList.findLast(t => t.id === item.datasourceId).name }}</el-tag>
          <el-tag v-if="item.requestUrl" effect="plain" style="text-align: center;margin-right: 12px;" type="success" class="drag-handle">{{ item.requestUrl }}</el-tag>
          <el-tag effect="plain" style="text-align: center;margin-right: 12px;" class="drag-handle">{{ index + 1 }}</el-tag>
        </template>
        <el-button size="mini" type="text" @click="handleDel(index)" style="float: right">删除</el-button>
        <page1 v-if="item.type == 1" :form="item" :hosts="hosts" :quoteList="list" />
        <page2 v-if="item.type == 2" :form="item" :datasourceList="datasourceList" :quoteList="list" />
        <page3 v-if="item.type == 3" :form="item" :list="item.childrenList" :hosts="hosts" :datasourceList="datasourceList" :quoteList="list" />
        <page4 v-if="item.type == 4" :form="item" :list="item.childrenList" :hosts="hosts" :datasourceList="datasourceList" :quoteList="list" />
      </el-collapse-item>
      </draggable>
    </el-collapse>
    <el-empty v-else/>
    <div class="footer">
      <el-button type="primary" @click="submit" v-if="isVisible">提 交</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <el-dialog title="操作日志详细" :visible.sync="open" >
      <div v-if="open">
        <report :sid="caseSID"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import {runCase} from "@/api/test/case";
import {listCaseStep, updateCaseStep} from "@/api/test/caseStep";
import page1 from "./page1.vue"
import page2 from "./page2.vue"
import page3 from "./page3.vue"
import page4 from "./page4.vue"
import {listHttp} from "@/api/test/http";
import {listDatasource} from "@/api/test/database";
import Report from "@/views/test/case/report/index.vue";

export default {
  dicts: ['step_type'],
  components: {Report, draggable, page1, page2, page3, page4},
  data() {
    return {
      id: '',
      isVisible: false,
      loading: false,
      open: false,
      activeName: null,
      list: [],
      hosts: [],
      datasourceList: [],
      caseSID: null,
    };
  },
  created() {
    this.loading = true;
    listHttp().then(res => {
      this.hosts = res.data;
    })
    listDatasource().then(res => {
      this.datasourceList = res.data;
    })
    listCaseStep({caseId: this.$route.query.id}).then(res => {
      this.list = [];
      res.data.forEach(item => {
        this.id = item.caseId;
        let childrenList = item.childrenList;
        if (childrenList) {
          childrenList.forEach((children) => {
            if (children.requestHeader === '[]') {
              children.requestHeader = [];
              children.requestHeader.push({
                key: "",
                value: "",
              })
            }
            if (children.requestParams === '[]') {
              children.requestParams = [];
              children.requestParams.push({
                key: "",
                value: "",
              })
            }
            if (children.assignment === '[]') {
              children.assignment = [];
              children.assignment.push({
                name: "",
                type: "",
                content: "",
                path: "",
              })
            }
            if (children.assertion === '[]') {
              children.assertion = [];
              children.assertion.push({
                name: "",
                source: "",
                fn: "",
                target: ""
              })
            }
          });
        }
        let p = {
          ...item,
          assertion: item.assertion ? JSON.parse(item.assertion) : [],
          assignment: item.assignment ? JSON.parse(item.assignment) : [],
          requestHeader: item.requestHeader ? JSON.parse(item.requestHeader) : [],
          requestParams: item.requestParams ? JSON.parse(item.requestParams) : []
        }
        p.assertion.push({
          name: "",
          source: "",
          fn: "",
          target: ""
        })
        p.assignment.push({
          name: "",
          type: "",
          content: "",
          path: "",
        })
        p.requestHeader.push({
          key: "",
          value: "",
        })
        p.requestParams.push({
          key: "",
          value: "",
        })
        this.list.push(p)
      })
      this.loading = false;
    });

  },
  methods: {
    caseEditVisible() {
      this.isVisible = true;
      this.$emit('data-from-child', false);
    },
    handleRun(id) {
      this.$modal.confirm('是否确认执行用例？').then(function () {
        return runCase(id);
      }).then(() => {
        this.$modal.msgSuccess("执行成功");
        this.caseSID = res.msg
        this.open = true;
      });
    },
    // 拖拽结束后更新排序值
    onDragEnd() {
      this.updateSortValues();
    },
    // 更新每行数据的 sort 值
    updateSortValues() {
      this.list.forEach((item, index) => {
        item.stepNum = index + 1;
        updateCaseStep({
          id: item.id,
          stepNum: item.stepNum,
        })
      });
    },
    handleAdd(type) {
      this.list.push({
        name: "",
        type: type,
        requestMethod: 'POST',
        requestUrl: "",
        apiHttpId: null,
        requestHeader: [{
          key: "",
          value: "",
        }],
        requestParams: [{
          key: "",
          value: "",
        }],
        assignment:[{
          name: "",
          type: "",
          content: "",
          path: "",
        }],
        assertion:[{
          name: "",
          source: "",
          fn: "",
          target: ""
        }],
        requestBody: "",
      });
    },
    submit() {
      this.isVisible = false;
      this.$emit('data-from-child', true);
      this.$emit("submit", this.list);
    },
    cancel() {
      this.isVisible = false;
      this.$tab.refreshPage({path: "/case/detail/?id=" + this.id})
      // this.$tab.closeOpenPage({path: "/case"});
    },
    handleDel(index) {
      this.list.splice(index, 1)
    }
  }
}
</script>

<style scoped lang="scss">
.footer {
  margin-top: 16px;
  text-align: right;
}
</style>
