<script lang="ts">
export default {
  name: "新增事故情景",
};
</script>

<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import { getDictItemById } from '@/api/dict';
import { eventsBatchSave } from '@/api/business/event';
import ConditionModel from '@/views/component/scenario/condition.vue'
import { addScenarios,updateScenarios} from "@/api/business/scenario";

const emit = defineEmits([ 'closeCreatescenario']);
const props = defineProps({ // 接收父组件传递的项目信息
  projectInfo: {
    required: true,
    type: Object,
    default: {}
  }
});
const isSwitch = ref(false); // 事故情景id
const infoForm = ref();
const scenarioId = ref(""); // 事故情景id
const algorithmTypeData: any = ref([]); // 算法类型数据
const dialogVisible = ref(true);
const stepsActive = ref(0); // 步骤导航栏当前激活的步骤索引
const info: any = ref({
  name: "",
  code: "",
  description: "",
});
const rules = ref({ // 
  name: [{ required: true, message: "请输入事故情景名称", trigger: "blur" }],
  algorithmType: [{ required: true, message: "请选择算法类型", trigger: "change" }],
});
function handleScenarioClose(){
  emit("closeCreatescenario",false)

}
const getAlgorithmType = async () => {
  try {
    let params = {
      dictId: '595502b91e7741b5033b53622d8731a3',
      size:99,
      current:1
    }
    const result:any = await getDictItemById(params);
    if (result.code == '0') {
      algorithmTypeData.value = result.data.records
    }
  } catch (error) {
  }
}
//新建事故情景-确认按钮/修改按钮
function confirmClick(formEl: any) {
  console.log(info.value)
  formEl.validate((valid: any) => {
    if (valid) {

      if (!info.value.scenarioId) {
        const params = {
          projectId: props.projectInfo.projectId,
          name: info.value.name,
          algorithmType: info.value.algorithmType,
          description: info.value.description,
        };
        if(isSwitch.value == true){
          return ;
        }
        isSwitch.value = true
        addScenarios(params).then((res:any) => {
          isSwitch.value = false;
          if(res && res.code == 0) {
            scenarioId.value = res.scenarioId;
            ElMessage({
              type: "success",
              message: "新增成功",
            });
            stepsActive.value = 1;
          } else {
            ElMessage({
              type: "error",
              message: "新增失败",
            });
          }
        }).catch(() => {
          isSwitch.value = false;
        })
      } else if (info.value.scenarioId) {
        const params = {
          scenarioId: info.value.scenarioId,
          projectId: info.value.projectId,
          name: info.value.name,
          algorithmType: info.value.algorithmType,
          description: info.value.description,
        };
        updateScenarios(params).then((res) => {

        });
      } else {
        return false;
      }
    }
  });
}
const conditionModel = ref()
function submitClick(){
  const tempData = conditionModel.value?.submitClick()
  let data:any = []
  tempData.forEach((item: any) => {
    data.push({
      triggerTime:'0',
      attrChanges:JSON.stringify(item) ,
      scenarioId: scenarioId.value
    })
  })

  eventsBatchSave(data).then((res:any) => {
    if (res.code == '0') {
      emit("closeCreatescenario",false)
      ElMessage({
        type: "success", 
        message: "新增失败",
      });
    }
  })

  
}
onMounted(() => {
  getAlgorithmType()
});
</script>
<template>
  <el-dialog v-model="dialogVisible" :close-on-click-modal="false"
    :modal="false" draggable :before-close="handleScenarioClose" title="新增事故情景"
      append-to-body width="1000px">
      <div class="scenario-setting-box">
        <el-steps style="width: 500px;margin:0 auto " :active="stepsActive" align-center>
          <el-step title="事故情景设置"/>
          <el-step title="初始条件设置" />
          <!-- <el-step title="确认模拟" /> -->
        </el-steps>
      </div>
      <div class="scenario-setting-bottombox">
        <el-form ref="infoForm" :model="info" :rules="rules" label-width="140px" style="width:600px" 
        v-if="stepsActive == 0">
            <el-form-item label="事故情景名称：" prop="name">
              <el-input v-model="info.name" style="width: 100%" placeholder="输入事故情景名称" ></el-input>
            </el-form-item>
            <el-form-item label="算法类型：" prop="algorithmType">
              <el-select v-model="info.algorithmType" placeholder="请选择" style="width:100%;" clearable>
                <el-option v-for="item in algorithmTypeData" :key="item.id" :label="item.dictName" :value="item.itemCode"  />
              </el-select>
            </el-form-item>
            <el-form-item label="事故情景描述：">
              <el-input type="textarea" v-model="info.description"  :rows="6" style="width: 100%" placeholder="请输入事故情景描述"></el-input>
            </el-form-item>
          </el-form>
          <ConditionModel v-if="stepsActive == 1" ref="conditionModel" :projectInfo="projectInfo" :scenarioId="scenarioId" />
      </div>
      <div style="text-align: center;">
        <el-button v-if="stepsActive == 0" type="primary" @click="confirmClick(infoForm)">下一步</el-button>
        <el-button v-else type="primary" @click="submitClick">下一步</el-button> 
      </div>
      
    </el-dialog>
</template>
<style>
.scenario-setting-bottombox{
  width: 900px;
  height: calc(100vh - 300px);
  background: inherit;
  background-color: rgba(255, 255, 255, 1);
  border: none;
  border-radius: 5px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
  margin: 20px auto;
  display: flex;
  justify-content: center;
  align-items: center;
}


</style>