<template>

  <div>

    <el-dialog
        title="添加测试用例"
        :visible.sync="dialogVisible"
        width="50%"
    >
      <span slot="footer" class="dialog-footer">
                    <el-tree
                        class='tree-padding'
                        :data="api_management_case_tree"
                        ref="tree"
                        show-checkbox
                        :highlight-current="true"
                        node-key="id"
                        :default-expand-all="false"
                        :load="loadNode"
                        :expand-on-click-node="false"
                        lazy
                        :default-expanded-keys="[]"
                        :default-checked-keys="[defaultCase]"
                        :props="defaultProps"
                    >
                      <span slot-scope="{ node, data }">
                        <span> <i :class="data.icon"></i>{{ node.label }} </span>
                      </span>
                </el-tree>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveApiScenariosTreeCase">确 定</el-button>
      </span>
    </el-dialog>
    <div>
      <el-form  ref="apiScenariosCaseFormRef" :model="apiScenariosCaseForm" label-width="150px">

        <el-form-item label="API场景测试名称" style="width: 50%;">
          <el-input v-model="apiScenariosCaseForm.api_scenarios_case_name"></el-input>
        </el-form-item>
        <el-form-item label="API场景测试描述">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="apiScenariosCaseForm.api_scenarios_case_describe"
              style="width: 50%;">
          </el-input>
        </el-form-item>
        <el-form-item >
          <el-input
              type="textarea"
              :rows="2"
              placeholder="API调式结果"
              :autosize="{ minRows: 3, maxRows: 4}"
              :readonly="true"
              v-model="api_scenarios_case_debug"
              style="width: 50%;">
          </el-input>
        </el-form-item>

        <el-form-item label="调试域名">
          <el-select  v-model="api_environment"  placeholder="请选择域名"  id="selectApiEnvironment" @change="getSelectApiEnvironmentFun">
            <el-option v-for="item in environmentSelect" :key="item.id" :value="item.id" :label="item.api_environment_name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="debugApiScenariosCase">调试</el-button>
          <el-button type="primary" @click="addApiScenariosCase">添加API用例</el-button>
        </el-form-item>

        <div class="container">
          <div class="drag-box">
            <div class="drag-box-item">
              <draggable v-model="apiScenariosCaseTableData">

                <el-table
                    :data="apiScenariosCaseTableData"
                    style="width: 100%"
                    :row-key="row_test"
                    class="api_scenarios_case_name_css"

                >
                  <el-table-column
                      prop="api_service_name"
                      label="API服务名称"
                      width="300">
                  </el-table-column>
                  <el-table-column
                      prop="api_module_name"
                      label="API模块名称"
                      width="300">
                  </el-table-column>
                  <el-table-column
                      prop="interfaces_name"
                      label="API接口名称"
                      width="300">
                  </el-table-column>
                  <el-table-column
                      prop="api_scenarios_case_name"
                      label="API用例名称"
                      width="300">
                  </el-table-column>

                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button size="mini" type="danger" @click="Delete(scope.$index, apiScenariosCaseTableData)" style="margin-left: 0px; margin-right: 13px; padding-right: 28px; text-align: center; ">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>

              </draggable>
            </div>
          </div>
        </div>

        <div class="page-element-class">
          <el-form-item>
            <el-button type="primary" @click="saveApiScenariosCase">保存</el-button>
            <el-button type="default" @click="cancelSaveApiScenariosCase">取消</el-button>
<!--            <el-button type="default" @click="sortingCase(apiScenariosCaseTableData)">自动排序</el-button>-->
          </el-form-item>
        </div>
      </el-form>

    </div>
  </div>

</template>

<script>
import {
  addApiScenariosCaseRequest,
  getApiScenariosCaseRequest,
  getSingleScenariosCaseRequest, postApiScenariosCaseRequest,
  postInterfacesScenariosCaseDeBugRequest, postServiceModuleInterfacesCaseRelationshipRequest,
  updateScenariosCaseRequest
} from "../../../../api/apiAutomation/apiScenariosCase";
import Sortable from 'sortablejs';
import {getApiEnvironmentRequest} from "../../../../api/apiAutomation/apiEnvironment";
import {postApiManagementTreeRequest} from "../../../../api/apiAutomation/apiManagement";
import draggable from 'vuedraggable'
export default {
  name: "addOrEditApiScenariosCase",
  props:['type', 'apiProjectId', 'apiScenariosCaseData'],
  components: {
    draggable
  },
  data() {
    return {
      dragging: false,
      api_management_case_tree: [],
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'isLeaf'
      },
      defaultCase: [],
      apiScenariosCaseForm: {
        api_scenarios_case_name: "",
        api_management_id: "",
        api_scenarios_case_id: 0,
        api_scenarios_case_describe: "",

      },
      apiScenariosCaseTableData: [
        // {
        //   api_interfaces_case_id: "",
        //   api_scenarios_case_name: "",
        //   steps: "",
        // }
      ],
      api_scenarios_case_debug: "",

      api_environment: '',
      api_environment_options:[
        {
          api_environment_describe:'',
          api_environment_name: '',
          api_title: '',
          id: ''

        }
      ],
      environmentSelect: [],

    }

  },
  methods:{
    row_test(row){
      return row.case_steps
    },

    loadNode(node, resolve) {
      if (node.level == 0) {
        console.log(node.level)
      }
      if (node.level > 4) {
        return resolve([]);
      }
      if (node.level >= 1 && node.level <=2) {
        let req = {
          "parent":node.data.id,
          "isLeaf": 'false'
        }
        postApiManagementTreeRequest(req).then(data => {
          if (true === data.data.success){
            this.resolve = data.data.data
            return resolve(data.data.data);
          }else {
            this.$message.error(data.data.message)
          }
        })
      }
      if (node.level == 3) {
        let req = {
          "parent":node.data.id
        }
        postApiScenariosCaseRequest(req).then(data => {
          if (true === data.data.success){

            data.data.data.forEach(item=>{
              if(true === item.isParent){
                item.isLeaf = true
              }
            })
            return resolve(data.data.data)
          }else {
            this.$message.error(data.data.message)
          }
        })
      }
    },

    // 添加api测试用例
    addApiScenariosCase(){

      this.dialogVisible = true

    },

    // 自动排序
    sortingCase(rows){
      for(let i=0;i<rows.length;i++){
        this.apiScenariosCaseTableData[i]['case_steps']= i
      }
    },

    //行拖拽
    rowDropCase() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.apiScenariosCaseTableData.splice(oldIndex, 1)[0]
          _this.apiScenariosCaseTableData.splice(newIndex, 0, currRow)
        }
      })
    },

    // 调试场景测试 debug
    debugApiScenariosCase() {
      this.sortingCase(this.apiScenariosCaseTableData)

      let req = JSON.parse(JSON.stringify(this.apiScenariosCaseForm));
      for(let i=0;i<this.apiScenariosCaseTableData.length;i++){
        let steps
        steps = this.apiScenariosCaseTableData[i]['case_steps']= i
      }

      req.api_scenarios_case_data=this.apiScenariosCaseTableData;
      req.environment = this.api_environment

      this.$refs.apiScenariosCaseFormRef.validate((valid) => {

        if (valid) { // 代表校验通过
          postInterfacesScenariosCaseDeBugRequest(req).then(data => {
            if (true === data.data.success) {
              this.api_scenarios_case_debug= data.data.data
              this.$message.success(data.data.data)
            } else {
              this.api_scenarios_case_debug = data.data.error.message
              this.$message.error(data.data.error.message)
            }
          })
        } else {  //校验失败
          return false;
        }

      });

    },

    // 取消
    cancelSaveApiScenariosCase(){
      this.$parent.cancelSaveScenariosCase();
    },

    //保存场景用例 tree节点
    saveApiScenariosTreeCase(rows){
      let req = this.$refs.tree.getCheckedNodes(false)
      for (let i=0; i<req.length;i++){
        if(req[i].hasOwnProperty("case_id")){

          let interfaces_relationship = {}

          interfaces_relationship.case_id = req[i].id
          // 更新场景用例列表
          postServiceModuleInterfacesCaseRelationshipRequest(interfaces_relationship).then(data => {
            if (true === data.data.success) {
              this.apiScenariosCaseTableData.push( {
                api_interfaces_case_id: req[i].id,
                api_scenarios_case_name: req[i].name,
                case_steps: "",
                api_module_name: data.data.data.api_module_name,
                interfaces_name: data.data.data.interfaces_name,
                api_service_name: data.data.data.api_service_name
              })

              this.sortingCase(this.apiScenariosCaseTableData)

              this.$refs.tree.setCheckedKeys([])
            } else {
              this.$message.error("获取失败")
            }
          })
        }

      }
      this.dialogVisible = false
    },

    // 保存
    saveApiScenariosCase(){
      if ('add' === this.type){
        this.addScenariosCase()
      }else {
        this.editScenariosCase()
      }

    },

    // 添加场景用例
    addScenariosCase(){
      let req = JSON.parse(JSON.stringify(this.apiScenariosCaseForm));
      for(let i=0;i<this.apiScenariosCaseTableData.length;i++){
        this.apiScenariosCaseTableData[i]['case_steps']= i
      }

      req.api_scenarios_case_data=this.apiScenariosCaseTableData;
      this.$refs.apiScenariosCaseFormRef.validate((valid) => {

        if (valid) { // 代表校验通过
          addApiScenariosCaseRequest(req).then(data => {
            if (true === data.data.success) {
              this.$message.success("添加Api场景测试成功")
            } else {
              this.$message.error("添加Api场景测试失败")
            }
          })
        } else {  //校验失败
          return false;
        }
        this.$parent.cancelSaveScenariosCase();

      });

    },

    // 编辑场景用例
    editScenariosCase(){
      let req = JSON.parse(JSON.stringify(this.apiScenariosCaseForm));
      for(let i=0;i<this.apiScenariosCaseTableData.length;i++){
        let steps
        steps = this.apiScenariosCaseTableData[i]['case_steps']= i
      }
      req.api_scenarios_case_data=this.apiScenariosCaseTableData;
      this.$refs.apiScenariosCaseFormRef.validate((valid) => {
        if (valid) { // 代表校验通过
          updateScenariosCaseRequest(this.apiScenariosCaseForm.api_scenarios_case_id, req).then(data => {
            if (true === data.data.success) {
              this.$message.success("编辑场景用例成功")
            } else {
              this.$message.error("编辑场景用例失败")
            }
          })
        } else {  //校验失败
          return false;
        }
        this.$parent.cancelSaveScenariosCase();
      });
    },



    // 删除行
    Delete(index, rows) {
      rows.splice(index, 1);

    },

    // 行号
    indexMethod(index) {
      return index;
    },

    // 获取域名
    getSelectApiEnvironmentFun(){
      getApiEnvironmentRequest().then(data =>{
        if (true === data.data.success) {

          this.environmentSelect = data.data.data;

        } else {
          this.$message.error("获取接口失败")
        }
      })


    },
    //获取单个场景测试用例列表
    getSingleScenariosCaseFun() {
      getSingleScenariosCaseRequest(this.apiScenariosCaseData.id).then(data => {
        if (true === data.data.success) {
          let apiScenariosCase= data.data.data;

          this.apiScenariosCaseTableData=[...apiScenariosCase];

        } else {
          this.$message.error("获取接口失败")
        }
      })
    },

    // 获取接口用例的树形结构
    get_api_scenarios_case_fun(){
      getApiScenariosCaseRequest().then(data => {
        if (true === data.data.success){
          this.api_management_case_tree = data.data.data
        }else {
          this.$message.error(data.data.message)
        }
      })
    },

  },
  created() {
    if ('edit'===this.type){
      this.apiScenariosCaseForm = {
        api_scenarios_case_name: this.apiScenariosCaseData.api_scenarios_case_name,
        api_management_id: this.apiProjectId,
        api_scenarios_case_id: this.apiScenariosCaseData.id,
        api_scenarios_case_describe: this.apiScenariosCaseData.api_scenarios_case_describe,

      }
      this.getSingleScenariosCaseFun()
      this.get_api_scenarios_case_fun();


    }
    if ('add'===this.type) {

      this.get_api_scenarios_case_fun();
      this.apiScenariosCaseForm.api_management_id = this.apiProjectId

    }
  },
  mounted(){
    this.getSelectApiEnvironmentFun()
    this.rowDropCase()
    this.indexMethod()
  },

}
</script>

<style scoped>

.tree-padding {
  padding-top: 10px;
  overflow:auto;
  max-height: 500px;
}

/deep/ .el-tree>.el-tree-node {
  display: inline-block;
  min-width: 100%;
}
/deep/.is-focusable{
  padding-bottom: 5px;
}

/deep/.el-tree {
  min-width: 100%;
  display: inline-block;
}
</style>