<template>
  <div>
    <el-form  ref="apiTestPlanFormRef" :model="apiTestPlanForm" label-width="100px">
      <el-form-item label="API测试任务"  prop="api_test_plan_name">
        <el-input v-model="apiTestPlanForm.api_test_plan_name"  class="api_test_plan_name" ></el-input>
      </el-form-item>

      <el-form-item label="描述" prop="api_test_plan_describe">
        <el-input type="textarea" v-model="apiTestPlanForm.api_test_plan_describe" style="width: 230px;"></el-input>
      </el-form-item>
      <el-form-item label="域名">
        <el-select  v-model="apiTestPlanForm.api_environment_id"  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 label="数据库">
        <el-select v-model="apiTestPlanForm.database_id" placeholder="请选择数据库"  @change="getSelectDatabaseFun" :clearable="true">
          <el-option v-for="database_option in database_options" :key="database_option.id" :label="database_option.api_database_title" :value="database_option.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="API场景测试用例">
        <el-tree
            :data="data"
            show-checkbox
            node-key="id"
            :props="defaultProps"

            ref="tree"
            @check-change="handleBucketClick"
            :default-expanded-keys="[]"
            :default-checked-keys="defaultTask"

            style="width: 500px;">
        </el-tree>
      </el-form-item>

      <el-form-item label="发送邮箱"  prop="api_send_email">
        <el-input v-model="apiTestPlanForm.api_send_email"  class="api_send_email" ></el-input>
      </el-form-item>

      <el-form-item label="企微监控"  prop="api_send_enterprise_wechat">
        <el-select v-model="apiTestPlanForm.api_send_enterprise_wechat" placeholder="请选择">
          <el-option v-for="api_send_enterprise_wechat_option in api_send_enterprise_wechat_options" :key="api_send_enterprise_wechat_option.value" :label="api_send_enterprise_wechat_option.text" :value="api_send_enterprise_wechat_option.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="定时任务"  prop="timing_task_status">
        <el-switch
            v-model="apiTestPlanForm.timing_task_status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="true"
            inactive-value="false"
        >
        </el-switch>
      </el-form-item>

      <div class="page-element-class">
        <el-form-item>
          <el-button type="primary" @click="saveApiTestPlan">保存</el-button>
          <el-button type="default" @click="cancelSaveApiTestPlan">取消</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>

</template>

<script>
import {getApiEnvironmentRequest} from "../../../../api/apiAutomation/apiEnvironment";
import {getDatabaseRequest} from "../../../../api/apiAutomation/apiDatabase";
import {
  addAPITestPlanRequest,
  getScenariosCaseTreeRequest,
  getSingleApiTestPlanRequest, updateSingleApiTestPlanRequest
} from "../../../../api/apiAutomation/apiTestPlan";
import {
  addAPITestTaskRequest,
  getSingleApiTestTaskRequest,
  updateSingleApiTestTaskRequest
} from "../../../../api/apiAutomation/apiTestTask";

export default {
  name: "addOrEditApiTestPlan",
  props: ['type', 'apiManagementId', 'apiTestPlanData', 'apiTestPlanId'],
  data(){
    return {
      apiTestPlanForm: {
        api_test_plan_name: "",
        api_test_plan_id: 0,
        api_test_plan_describe: "",
        api_send_email: "",
        api_send_enterprise_wechat: "",
        api_environment_id: "",
        database_id: "",
        time_interval_hours: '0',
        time_interval_minutes: '0',
        time_interval_seconds: '0',
        time_interval_day: '0',
        timing_task_status: '0',
      },
      api_management_id: 0,
      time_range: [],
      api_send_enterprise_wechat_options: [
        { text: '请选择',
          value: 0
        },
        { text: '是',
          value: 1
        },
        { text: '否',
          value: 2
        },
      ],
      api_environment_id: '',
      environmentSelect: [],
      database_options: [],
      count:"",//倒计时

      data: [],

      defaultProps: {
        label: "label",
        children: "children"

      },

      cases: [],
      defaultTask: [],
      api_project_id: ""

    }

  },
  methods: {

    //取消保存测试任务
    cancelSaveApiTestPlan(){

      this.$parent.cancelSaveTestPlan()

    },

    //创建/编辑-保存测试任务
    saveApiTestPlan(){
      if ('add'===this.type){
        this.addApiTestPlan()

      }else {
        this.editApiTestPlan()
      }


    },

    //编辑测试计划
    editApiTestPlan(){
      let req = JSON.parse(JSON.stringify(this.apiTestPlanForm));
      let case_id = this.$refs.tree.getCheckedNodes(true)
      console.log(case_id)
      this.cases = []
      for (let i=0; i<case_id.length;i++){
        this.cases[i] = case_id[i].api_scenarios_case_id

      }

      req.cases = this.cases
      req.api_management_id =  this.api_management_id
      req.starting_time = this.time_range[0]
      req.end_time = this.time_range[1]
      this.$refs.apiTestPlanFormRef.validate((valid) => {
        if (valid) { // 代表校验通过
          updateSingleApiTestPlanRequest(this.apiTestPlanForm.api_test_plan_id, req).then(data => {
            if (true === data.data.success) {
              this.showAddOrEditApiTestPlan = false;
              this.$message.success("编辑API测试计划成功")
              this.$parent.cancelSaveTestPlan()
            } else {
              this.$message.error("编辑API测试计划失败")
            }
          })
        } else {  //校验失败
          return false;
        }

      });
    },

    //创建测试计划
    addApiTestPlan(){
      this.apiTestPlanForm.api_test_plan_id = 0;

      let req = JSON.parse(JSON.stringify(this.apiTestPlanForm));

      let case_id = this.$refs.tree.getCheckedNodes(true)
      this.cases = []
      for (let i=0; i<case_id.length;i++){
        this.cases[i] = case_id[i].api_scenarios_case_id

      }
      req.cases = this.cases
      req.api_management_id =  this.api_management_id
      req.starting_time = this.time_range[0]
      req.end_time = this.time_range[1]


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

        if (valid) { // 代表校验通过
          addAPITestPlanRequest(req).then(data => {
            if (true === data.data.success) {
              this.showAddOrEditApiTestPlan = false;
              this.$message.success("添加API测试计划成功")
              console.log(this.$parent)
              this.$parent.cancelSaveTestPlan()

            } else {
              this.$message.error("添加APi测试计划失败")
            }
          })
        } else {  //校验失败
          return false;
        }

      });

    },

    //获取场景测试用例树形结构
    getScenariosCaseTreeFun(){
      getScenariosCaseTreeRequest(this.api_management_id).then(data =>{
        if (true === data.data.success){
          let apiTestPlan = data.data.data;
          let req = JSON.parse(JSON.stringify(apiTestPlan));
          for(var i =0;i<req.length;i++){
            let children = req[i].children
            req[i].label = req[i].api_project_name

            for(var j=0;j<children.length;j++){
              req[i].children[j].label = req[i].children[j].api_scenarios_case_name
              req[i].children[j].id = req[i].children[j].api_scenarios_case_id
            }
          }
          this.data = req
        }else {
          this.$message.error("获取接口失败")
        }

      })

    },

    handleBucketClick(data){

    },

    // 获取域名
    getSelectApiEnvironmentFun(){
      getApiEnvironmentRequest().then(data =>{
        if (true === data.data.success) {
          this.environmentSelect = data.data.data;
        } else {
          this.$message.error("获取接口失败")
        }
      })


    },
    //获取数据库
    getSelectDatabaseFun(){
      getDatabaseRequest().then(data =>{
        if (true === data.data.success) {
          this.database_options = data.data.data;
        } else {
          this.$message.error("获取接口失败")
        }
      })
    },

    // 获取单独Api测试计划信息
    getSingleApiTestPlanFun() {
      getSingleApiTestPlanRequest(this.apiTestPlanForm.api_test_plan_id).then(data =>{
        if (true === data.data.success){

          this.defaultTask = JSON.parse(data.data.data.cases)

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

      })
    },

  },
  created() {
    if ('add'===this.type) {
      this.getSelectApiEnvironmentFun()
      this.getSelectDatabaseFun()
      this.api_management_id = this.apiManagementId
      this.getScenariosCaseTreeFun()

    }
    if ('edit'===this.type){
      this.api_management_id = this.apiManagementId
      this.apiTestPlanForm = {
        api_test_plan_name: this.apiTestPlanData.api_test_plan_name,
        api_test_plan_id: this.apiTestPlanId,
        api_test_plan_describe: this.apiTestPlanData.api_test_plan_describe,
        api_send_email: this.apiTestPlanData.api_send_email,
        api_send_enterprise_wechat: this.apiTestPlanData.api_send_enterprise_wechat,
        api_environment_id: this.apiTestPlanData.api_environment_id,
        database_id: this.apiTestPlanData.database_id,
        time_interval_hours: '0',
        time_interval_minutes: '0',
        time_interval_seconds: '0',
        time_interval_day: '0',
        timing_task_status: this.apiTestPlanData.timing_task_status,
      }
      this.time_range = [this.apiTestPlanData.starting_time, this.apiTestPlanData.end_time]

      this.getSelectApiEnvironmentFun()
      this.getSelectDatabaseFun()
      this.getScenariosCaseTreeFun()

      this.getSingleApiTestPlanFun()


    }

  }
}
</script>

<style scoped>

.api_test_plan_name{
  width: 230px;
}
.api_send_email{
  width: 230px;
}

</style>