<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 ConditionModels from '@/views/component/scenario/condition.vue'
import { addScenarios,updateScenarios,getActiveAlgorithms } from "@/api/business/scenario";
import { topologyDevicesLsit } from '@/api/business/project';
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" }],
  keffThreshold: [{ required: true, message: "请输入keff阈值", trigger: "blur" }],
});
function handleScenarioClose(){
  emit("closeCreatescenario",false)

}
const getAlgorithmType = async () => {
  try {
    const result:any = await getActiveAlgorithms();
      algorithmTypeData.value = result
  } catch (error) {
  }
}
//新建事故情景-确认按钮/修改按钮
function confirmClick(formEl: any) {
  console.log(info.value)
  formEl.validate((valid: any) => {
    if (valid) {

      if (!info.value.scenarioId) {
        const params:any = {
          projectId: props.projectInfo.projectId,
          name: info.value.name,
          algorithmType: info.value.algorithmType,
          description: info.value.description,
          keffThreshold: info.value.keffThreshold,
        };
        let device_algo_config:any = {}
        let isTrue:any = false
        deviceData.value.forEach((item: any) => {
          if(item.algorithmType !=null && item.algorithmType != ''){
            device_algo_config[item.deviceId] = item.algorithmType
            isTrue = true
          }
        })
        if(isTrue == true){
           params.deviceAlgoConfig = JSON.stringify(device_algo_config)
        }
        
        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:any = {
          scenarioId: info.value.scenarioId,
          projectId: info.value.projectId,
          name: info.value.name,
          algorithmType: info.value.algorithmType,
          description: info.value.description,
          keffThreshold: info.value.keffThreshold,
        };

         let device_algo_config:any = {}
        let isTrue:any = false
        deviceData.value.forEach((item: any) => {
          if(item.algorithmType !=null && item.algorithmType != ''){
            device_algo_config[item.deviceId] = item.algorithmType
            isTrue = true
          }
        })
        if(isTrue == true){
           params.deviceAlgoConfig = JSON.stringify(device_algo_config)
        }
        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: "新增成功",
      });
    }
  })

  
}
const deviceData: any = ref([]); // 设备数据
function initDeviceData(){
  deviceData.value = []
  topologyDevicesLsit({
    id: props.projectInfo.projectId
  }).then((res:any) => {
    if (res.code == 0) {
      res.data.forEach((item: any) => {
        deviceData.value.push({
          deviceId: item.deviceId,
          deviceName: item.deviceName,
          algorithmType: ''
        })
      })
    }
  })
}
onMounted(() => {
  initDeviceData()
  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="160px" style="width:600px;height: calc(100vh - 300px);overflow: auto;padding-top: 10px;" 
        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.algorithmType" :label="item.name" :value="item.algorithmType"  />
              </el-select>
            </el-form-item>

            <el-form-item label="设备算法配置映射：">
              <div style="width: 100%;padding-top: 40px;">
                <div v-for="item in deviceData" :key="item.deviceId" style="display: flex;align-items: center;margin-bottom: 10px;">
                  <div style="width: 150px;text-align: right;padding-right: 10px;">{{item.deviceName}}</div>
                  <el-select v-model="item.algorithmType" placeholder="请选择" style="width:100%;" clearable>
                    <el-option v-for="item in algorithmTypeData" :key="item.algorithmType" :label="item.name" :value="item.algorithmType"  />
                  </el-select>
                </div>
              </div>
            
             
            </el-form-item>

            <el-form-item label="Keff预警阈值：" prop="keffThreshold">
              <el-input v-model="info.keffThreshold" style="width: 100%" placeholder="输入Keff预警阈值" ></el-input>
            </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>
          <ConditionModels v-if="stepsActive == 1" ref="conditionModel" :projectInfo="projectInfo" :scenarioId="scenarioId" :isEdit="true"/>
      </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>