<!-- 报警规则添加列表 -->
<template>
  <div class="layout-pd">
    <el-dialog v-model="Data.isShowDialog" style="width: 75%;">
      <!--操作-->
      <div style="width: 100%;display: flex;justify-content: left;align-items: center;">
        <h1 style="margin-bottom: 10px;font-size: 30px;">报警推送规则</h1>
      </div>
      <div style="margin-bottom: 10px ;">
        <hr />
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="规则名称：" style="width: 100%;" prop="ruleName">
            <el-input v-model="Data.Filter.ruleName" style="width: 100%;" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="标签：" style="width: 100%;" prop="labelId">
            <el-select v-model="Data.Filter.labelId" placeholder="请选择标签">
              <el-option v-for="item in Data.labelList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="推送用户：" style="width: 100%;" prop="pushUserid">
            <el-select
              v-model="Data.Filter.pushUserid"
              placeholder="请选择用户"
              multiple
              style="width: 100%;"
            >
              <el-option-group
                v-for="(group, index) in Data.userList"
                :key="index"
                :label="`角色：${group.roleName}`"
              >
                <el-option
                  v-for="user in group.users"
                  :key="user.id"
                  :label="`${user.name}`"
                  :value="user.id"
                >
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="备&#8195;&#8195;注：" style="width: 100%;">
            <el-input type="textarea" rows="5" v-model="Data.Filter.remark" style="width: 100%;" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="推送方式：" style="width: 100%;" prop="pushMethod">
            <el-row style="width: 100%;">
              微信公众号<el-switch v-model="Data.radioValue1" style="margin-left: 3%;" @change="radioChange" />
            </el-row>
            <el-row style="width: 100%;">
              邮&#8195;&#8195;&#8195;箱<el-switch v-model="Data.radioValue2" style="margin-left: 3%;" @change="radioChange" />
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="模&#8195;&#8195;板：" style="width: 50%;" prop="mode1">
            <el-select v-model="Data.mode1" class="m-2" placeholder="微信模板" v-if="Data.radioValue1" @change="modeChange">
              <el-option v-for="item in templateData.wxList" :key="item.id" :label="item.templateName" :value="item.templateName" />
            </el-select>
          </el-form-item>
          <el-form-item label="&#8195;&#8195;&#8195;&#8195;" style="width: 100%;" prop="mode2">
            <el-select v-model="Data.mode2" class="m-2" placeholder="邮箱模板" v-if="Data.radioValue2" @change="modeChange">
              <el-option v-for="item in templateData.emailList" :key="item.id" :label="item.name" :value="item.templateName" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="正则匹配：" style="width: 100%;">
            <el-input type="textarea" rows="2" v-model="Data.Filter.regular" style="width: 100%;" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="关键字匹配：" style="width: 100%;">
            <el-input type="textarea" rows="5" v-model="Data.Filter.keyWord" style="width: 100%;" placeholder="如有多个关键字，请用英文“,”分割" />
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="&#8195;优先级:" style="width: 100%;" prop="taskPriority">
            <el-input-number v-model="Data.Filter.taskPriority" :controls="false" :min=1 :max=9 />
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 报警条件配置 -->
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="报警条件配置" style="width: 100%;">
          </el-form-item>
        </el-form>
      </div>
      <!-- <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="触发方式:" style="width: 100%;" prop="triggerMethod">
            <el-radio-group v-model="Data.Filter.triggerMethod">
              <el-radio label="0">其中之一条件满足即触发</el-radio>
              <el-radio label="1">全部满足时触发</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

            <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="互&#8195;&#8195;斥：" style="width: 100%;">
            <el-switch v-model="Data.Filter.isExclusive" />
          </el-form-item>
        </el-form>
      </div> -->
      
      <!-- 条件部分 - 初始不显示，点击添加按钮后才显示 -->
      <div v-if="Data.showAlarmConditions">
        <div v-for="(condition, index) in Data.condition" :key="index" 
             style="width: 100%;display: flex;justify-content: center;align-items: center; margin-top: 10px;">
          <el-form :inline="true" @submit.stop.prevent :model="condition" :rules="conditionRules">
            <el-form-item :label="index === 0 ? '条&#8195;&#8195;件:' : '附加条件:'" style="width: 130%; ">
              <el-row :gutter="20" style="width: 100%;">
                <!-- 报警设备 -->
                <el-col :span="8">
                  <div style="flex:1;">
                     <!-- style="display: flex; align-items: center;" -->
                    <span style="margin-right: 13px;">报警设备:</span>
                    <el-form-item prop="Left" style="display:flex">
                      <el-select v-model="condition.Left" placeholder="请选择" >
                        <el-option 
                          v-for="item in Data.alarmEquipment" 
                          :key="item" 
                          :label="item" 
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
                
                <!-- 报警类型 -->
                <el-col :span="8">
                  <div style="flex:1;">
                    <span style="margin-right: 13px;">报警类型:</span>
                    <el-form-item prop="inthe"  style="display:flex">
                      <el-select v-model="condition.inthe" placeholder="请选择" >
                        <el-option 
                          v-for="item in Data.alarmType" 
                          :key="item" 
                          :label="item" 
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
                
                <!-- 报警来源 -->
                <el-col :span="8">
                  <div style="flex:1;">
                    <span style="margin-right: 13px;">报警来源:</span>
                    <el-form-item prop="Right" style="display:flex">
                      <el-select v-model="condition.Right" placeholder="请选择">
                        <el-option 
                          v-for="item in Data.alarmSource" 
                          :key="item" 
                          :label="item" 
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 添加按钮 -->
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-button type="primary" icon="ele-Plus" style="font-size: large" @click="addCondition" />
        <el-button v-if="Data.condition.length > 1" type="primary" icon="ele-Minus" style="font-size: large" @click="removeCondition" />
      </div>

      <!-- 维修条件配置 -->
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="维修条件配置" style="width: 100%;">
          </el-form-item>
        </el-form>
      </div>
      <!-- <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="触发方式:" style="width: 100%;" prop="maintenanceTriggerMethod">
            <el-radio-group v-model="Data.Filter.maintenanceTriggerMethod">
              <el-radio label="0">其中之一条件满足即触发</el-radio>
              <el-radio label="1">全部满足时触发</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent>
          <el-form-item label="互&#8195;&#8195;斥：" style="width: 100%;">
            <el-switch v-model="Data.Filter.isExclusiveMaintenance" />
          </el-form-item>
        </el-form>
      </div> -->

      <!-- 维修条件部分 - 初始不显示，点击添加按钮后才显示 -->
      <div v-if="Data.showRepairConditions">
        <div v-for="(condition2, index) in Data.condition2" :key="index" 
             style="width: 100%;display: flex;justify-content: center;align-items: center; margin-top: 10px;">
          <el-form :inline="true" @submit.stop.prevent :model="condition2" :rules="condition2Rules">
            <el-form-item :label="index === 0 ? '条&#8195;&#8195;件:' : '附加条件:'" style="width: 130%;">
              <el-row :gutter="20" style="width: 100%;">
                <el-col :span="8">
                  <div style="flex:1;">
                    <span style="margin-right: 13px;">维修类型：</span>
                    <el-form-item prop="Left" style="display:flex">
                      <el-select v-model="condition2.Left" placeholder="请选择">
                        <el-option 
                          v-for="item in Data.alarmproType" 
                          :key="item" 
                          :label="item" 
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
                
                <el-col :span="8">
                  <div style="flex:1;">
                    <span style="margin-right: 13px;">维修状态：</span>
                    <el-form-item prop="Right" style="display:flex">
                      <el-select v-model="condition2.Right" placeholder="请选择" >
                        <el-option 
                          v-for="item in Data.alarmproStatus" 
                          :key="item" 
                          :label="item" 
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 添加按钮 -->
      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-button type="primary" icon="ele-Plus" style="font-size: large" @click="addRepairCondition" />
        <el-button v-if="Data.condition2.length > 1" type="primary" icon="ele-Minus" style="font-size: large" @click="removeCondition2" />
      </div>

      <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
        <el-form :inline="true" @submit.stop.prevent style="width: 60%;">
          <el-row justify="end" style="margin-top: 30px;">
            <el-button type="primary" @click="submitForm">保存</el-button>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="">
import { onMounted, reactive, ref, watch } from 'vue';
import { CirclePlusFilled } from '@element-plus/icons-vue'
import { alarmRluesFilterModel } from "/@/api/admin/AlarmService/alarmRulesDto";
import { alarmRulesApi } from "/@/api/admin/AlarmService/alarmRulesApi";
import { RoleApi } from '/@/api/admin/Role'
import { pushTemplateApi } from "/@/api/admin/AlarmService/pushTemplateApi";
import { TemplateFilterDto } from "/@/api/admin/AlarmService/pushTemplateDto";
import eventBus from "/@/utils/mitt";
import { ElMessage, type FormRules } from 'element-plus'
import { UserListItem } from "/@/api/admin/AlarmService/alarmRulesDto"; // 用户数据类型
import { URLSearchParams } from 'url';

// 条件验证规则
const conditionRules = reactive<FormRules>({
  Left: [{ required: true, message: '请选择报警设备', trigger: 'change' }],
  inthe: [{ required: true, message: '请选择报警类型', trigger: 'change' }],
  Right: [{ required: true, message: '请选择报警来源', trigger: 'change' }]
})

const condition2Rules = reactive<FormRules>({
  Left: [{ required: true, message: '请选择维修类型', trigger: 'change' }],
  Right: [{ required: true, message: '请选择维修状态', trigger: 'change' }]
})

const Data = reactive({
  isShowDialog: false,
  showAlarmConditions: false, // 控制报警条件显示
  showRepairConditions: false, // 控制维修条件显示
  Filter: {
    ruleName: '',
    roleMappingId: [],
    labelId: "",
    remark: '',
    pushMethod: '',
    pushTemplateMappingID: [],
    regular: '',
    keyWord:"",
    isExclusive: false,
    isExclusiveMaintenance: false,
    taskPriority: 1,
    triggerMethod: null, // 这里应根据实际情况设置默认值，比如0表示其中之一条件满足即触发
    maintenanceTriggerMethod:null,
    conditionsJson: '' as any,
    maintenanceJson: '' as any,
    pushUserid: [] as number[], // 选中的用户ID数组
    userName:"",
    userPhone:"",
    userId:"",
    condition2:"",
    condition:"",
    mode1:''
  } as unknown as alarmRluesFilterModel,
  /** 角色列表 */
  roleList: [] as any,
  // 标签列表
  labelList: [] as any,
  userList: [] as UserListItem[], // 用户列表
  /** 推送方式绑定数据 */
  radioValue1: false,
  radioValue2: false,
  /** 模板绑定数据 */
  mode1: '',
  mode2: '',
  /** 条件选择 */
  condition: [{
    Left: '',
    inthe: '',
    Right: ''
  }],
  condition2: [{
    Right: '',
    Left: ''
  }],
  alarmEquipment: ["安全装置","编码器","计控主板","监控微处理器","智能型控制阀","油气回收控制板","显示屏","计量器","加油机","油枪"],
  alarmType: ["加油机离线","通信异常","非法部件","厂商不符","绑定错误","监控微处理器报警","安全装置报警","加油机报警","检定"],
  alarmSource: ['云平台', '安全装置'],
  alarmproType: ["油机维修","装置维修"],
  alarmproStatus: ["正在维修","结束维修"]
})

const getUserList = async () => {
  try {
    const res = await new alarmRulesApi().getWxUserRole({});
    console.log('getWxUserRole接口返回数据:', res);
    const userDataArray = res.data || [];
    const userMap = new Map<string, UserListItem[]>();
    userDataArray.forEach((roleObj) => {
      const roleName = roleObj.roleName;
      roleObj.users.forEach((userObj) => {
        if (!userMap.has(roleName)) {
          userMap.set(roleName, []);
        }
        userMap.get(roleName).push({
          id: userObj.id,
          name: userObj.name,
          roleName: roleName
        });
      });
    });
    const groupedUsers = Array.from(userMap.entries()).map(([role, users]) => ({
      roleName: role,
      users: users
    }));
    Data.userList = groupedUsers;
    console.log('处理后的用户列表:', Data.userList);
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("用户列表加载失败");
  }
};

const templateData = reactive({
  Filter: {
    currentPage: 0,
    pageSize: 0,
    filter: {
      templateName: "",
      templateType: "",
      templateContent: "",
      id: 0
    }
  } as TemplateFilterDto,
  wxList: [] as any,
  emailList: [] as any
})

const radioChange = (() => {
  if (Data.radioValue1 == true) {
    Data.Filter.pushMethod = 'wx'
    if (Data.radioValue2 == true) {
      Data.Filter.pushMethod += ',email'
    }
  } else {
    if (Data.radioValue2 == true) {
      Data.Filter.pushMethod = 'email'
    } else {
      Data.Filter.pushMethod = ''
    }
  }
})

// 获取报警标签
const getLabel = async () => {
  try {
    const res = await new RoleApi().getLabel({
      currentPage: 1,
      pageSize: 100,
      filter: {
        dictTypeId: 677693042573381 // 报警标签的字典类型ID
      }
    })
    Data.labelList = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.name
    })) || []
  } catch (error) {
    console.error('获取标签失败:', error)
    Data.labelList = []
  }
}

// 获取角色列表
const getRole = async () => {
  const res = await new RoleApi().getList()
  Data.roleList = res.data?.map(item => {
    return { 'id': item.id, 'name': item.name }
  })
}

// 查询模板信息
const funSelect = async () => {
  const res = await new pushTemplateApi().getData(templateData.Filter)
  const data = res?.data
  templateData.wxList = (data as any)?.filter((item: any) => {
    if (item.templateType == "微信") {
      return { 'id': item.id, 'name': item.templateName }
    }
  })
  templateData.emailList = (data as any)?.filter((item: any) => {
    if (item.templateType == "邮箱") {
      return { 'id': item.id, 'name': item.templateName }
    }
  })
}

// 获取模板元素id
const modeChange = (() => {
  const wxItem = templateData.wxList.filter(item => item.templateName === Data.mode1)
  const emailItem = templateData.emailList.filter(item => item.templateName === Data.mode1)
  
  console.log(Data.mode1,wxItem,emailItem,templateData.wxList,templateData.emailList)
  Data.Filter.pushTemplateMappingID = []
  if (!Data.Filter.pushTemplateMappingID.includes(Number(wxItem[0].id))) {
    Data.Filter.pushTemplateMappingID?.push(Number(wxItem[0].id))
  }
  if (!Data.Filter.pushTemplateMappingID.includes(Number(emailItem[0].id))) {
    Data.Filter.pushTemplateMappingID?.push(Number(emailItem[0].id))
  }
})

onMounted(() => {
  getLabel();
  getRole();
  funSelect();
  getUserList(); // 初始化时获取用户列表
});

// 添加报警条件
const addCondition = () => {
  // 第一次点击添加按钮时显示条件区域
  if (!Data.showAlarmConditions) {
    Data.showAlarmConditions = true
  } else {
    // 验证当前条件是否已填写
    const lastCondition = Data.condition[Data.condition.length - 1]
    if (!lastCondition.Left || !lastCondition.inthe || !lastCondition.Right) {
      ElMessage.warning('请先填写当前条件的所有字段')
      return
    }
    
    // 添加新条件
    Data.condition.push({
      Left: '',
      inthe: '',
      Right: ''
    })
  }
}

// 添加维修条件
const addRepairCondition = () => {
  // 第一次点击添加按钮时显示条件区域
  if (!Data.showRepairConditions) {
    Data.showRepairConditions = true
  } else {
    // 验证当前条件是否已填写
    const lastCondition = Data.condition2[Data.condition2.length - 1]
    if (!lastCondition.Left || !lastCondition.Right) {
      ElMessage.warning('请先填写当前条件的所有字段')
      return
    }
    
    // 添加新条件
    Data.condition2.push({
      Left: '',
      Right: ''
    })
  }
}

// 删除报警条件
const removeCondition = () => {
  if (Data.condition.length > 1) {
    Data.condition.pop()
  } else {
    Data.showAlarmConditions = false
    Data.condition = [{
      Left: '',
      inthe: '',
      Right: ''
    }]
  }
}

// 删除维修条件
const removeCondition2 = () => {
  if (Data.condition2.length > 1) {
    Data.condition2.pop()
  } else {
    Data.showRepairConditions = false
    Data.condition2 = [{
      Left: '',
      Right: ''
    }]
  }
}

// 提交表单
const submitForm = async () => {
  // 验证必填字段
  if (!Data.Filter.ruleName) {
    ElMessage.warning('请输入规则名称')
    return
  }
  // if (!Data.Filter.labelId) {
  //   ElMessage.warning('请选择标签')
  //   return
  // }
  if (!Data.Filter.pushUserid || Data.Filter.pushUserid.length === 0) {
    ElMessage.warning('请选择推送用户')
    return
  }
  if (Data.radioValue1 && !Data.mode1) {
    ElMessage.warning('请选择微信模板')
    return
  }
  if (Data.radioValue2 && !Data.mode2) {
    ElMessage.warning('请选择邮箱模板')
    return
  }
  // if (Data.Filter.taskPriority < 1 || Data.Filter.taskPriority > 9) {
  //   ElMessage.warning('请设置有效的优先级(1-9)')
  //   return
  // }
  // if (Data.Filter.triggerMethod === null) {
  //   ElMessage.warning('请选择报警触发方式')
  //   return
  // }
  // if (Data.Filter.triggerMethod2 === null) {
  //   ElMessage.warning('请选择维修触发方式')
  //   return
  // }
  
  // 验证条件
  if (Data.showAlarmConditions) {
    for (const cond of Data.condition) {
      if (!cond.Left || !cond.inthe || !cond.Right) {
        ElMessage.warning('请填写所有报警条件字段')
        return
      }
    }
  }
  if (!Data.Filter.pushUserid || Data.Filter.pushUserid.length === 0) {
    ElMessage.warning('请选择推送用户');
    return;
  }
  
  let pushUserIds = Data.Filter.pushUserid;
  if (!Array.isArray(pushUserIds)) {
    pushUserIds = [pushUserIds]; // 转换为数组
  }

  if (Data.showRepairConditions) {
    for (const cond of Data.condition2) {
      if (!cond.Left || !cond.Right) {
        ElMessage.warning('请填写所有维修条件字段')
        return
      }
    }
  }
  
  // // 如果没有添加任何条件
  // if (!Data.showAlarmConditions && !Data.showRepairConditions) {
  //   ElMessage.warning('请至少添加一种条件')
  //   return
  // }
  
  // 准备提交数据
  const submitData = {
    ...Data.Filter,
    conditionsJson: Data.showAlarmConditions ? JSON.stringify(Data.condition) : null,
    maintenanceJson: Data.showRepairConditions ? JSON.stringify(Data.condition2) : null,
    pushUserid: pushUserIds,
  }
  
  console.log('提交数据', submitData)
  try {
    await new alarmRulesApi().addForm(submitData)
    ElMessage.success('保存成功')
    eventBus.emit('refreshView')
    Data.isShowDialog = false
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}
/**
 * 根据参数 打开表单
 * @param row
 */
const openDialog = (row: alarmRluesFilterModel) => {
  console.log(row)
  if(row){
    const { triggerMethod, maintenanceTriggerMethod, ruleName, roleMappingId, labelId,pushUserid,condition,condition2,isExclusive,isExclusiveMaintenance,regular,keyWord,...rest } = Data.Filter;
    Data.Filter = { ...rest, ...row };
    Data.Filter.triggerMethod = triggerMethod || Data.Filter.triggerMethod;
    Data.Filter.maintenanceTriggerMethod = maintenanceTriggerMethod || Data.Filter.maintenanceTriggerMethod;
    Data.Filter.roleMappingId = roleMappingId || Data.Filter.roleMappingId;
    Data.Filter.condition2 = condition2 || Data.Filter.condition2;
    Data.Filter.condition = condition || Data.Filter.condition;
    Data.Filter.labelId = labelId || Data.Filter.labelId;
    Data.Filter.ruleName = ruleName || Data.Filter.ruleName;
    Data.Filter.pushUserid = pushUserid || Data.Filter.pushUserid;
    Data.Filter.regular = regular || Data.Filter.regular;
    Data.Filter.keyWord = keyWord || Data.Filter.keyWord;

    Data.Filter.isExclusive = Boolean(row.isExclusive);
    Data.Filter.isExclusiveMaintenance = Boolean(row.isExclusiveMaintenance);



    Data.Filter.pushUserid = Array.isArray(row.pushUserid) 
      ? row.pushUserid 
      : [row.pushUserid || 0]; // 处理可能的非数组情况

    if(row.pushTemplateMappingID != undefined && row.pushTemplateMappingID.length > 0) {
      const id = row.pushTemplateMappingID[0]
      const wxItem = templateData.wxList.filter(item => item.id === id);
      const emailItem = templateData.emailList.filter(item => item.id === id);
     
      if(wxItem != undefined) {
        Data.mode1 = wxItem[0].templateName
      } else {
        Data.mode1 = emailItem[0].templateName
      }
     
    }
 
    


    const temp = <string[]>Data.Filter.pushMethod?.split(',');
    for (var i = 0; i < temp.length; i++) {
      if (temp[i] == '微信') {
        Data.radioValue1 = true;
      } else if (temp[i] == '电子邮箱') {
        Data.radioValue2 = true;
      }
    }

    // 如果有条件数据，解析并显示
    // 解析报警条件
    if (row.conditionsJson) {
      try {
        const alarmConditions = JSON.parse(row.conditionsJson);
        if (alarmConditions && alarmConditions.length > 0) {
          Data.condition = alarmConditions;
          Data.showAlarmConditions = true;
        }
      } catch (e) {
        console.error('解析报警条件JSON失败:', e);
      }
    }

    // 解析维修条件
    if (row.maintenanceJson) {
      try {
        const repairConditions = JSON.parse(row.maintenanceJson);
        if (repairConditions && repairConditions.length > 0) {
          Data.condition2 = repairConditions;
          Data.showRepairConditions = true;
        }
      } catch (e) {
        console.error('解析维修条件JSON失败:', e);
      }
    }

    console.log(Data.Filter,Data.mode1)
  } else {
    Data.Filter = {
      ruleName: '',
      roleMappingId: [],
      labelId: null,
      remark: '',
      pushMethod: '',
      pushTemplateMappingID: [],
      regular: '',
      keyWord:'',
      isExclusive: false,
      isExclusiveMaintenance: false,
      taskPriority: 1,
      triggerMethod: null,
      conditionsJson: null,
      maintenanceJson: null,
      maintenanceTriggerMethod:null,
      pushUserid: []
    } as unknown as alarmRluesFilterModel;
    Data.mode1 = "",
    Data.condition = [{
    Left: '',
    inthe: '',
    Right: ''
  }]
    Data.showAlarmConditions = false
    Data.condition2 = [{
    Left: '',
    inthe: '',
    Right: ''
  }]
    Data.showRepairConditions = false
  }

  Data.isShowDialog = true;
  
    console.log("打开弹窗的数据：" ,Data.Filter)
};

defineExpose({
  openDialog,
})
</script>

<style scoped lang="scss">
.my-el-link {
  font-size: 12px;
}

.el-form {
  width: 60%;
}

.el-form .el-col{
  margin: 0 !important;
}

/* 输入框标签固定四个字符宽度 */
::v-deep .el-form-item__label {
  width: 100px;
  justify-content: start;
}

.el-input {
  width: 240px;
}

.el-select .el-input {
  width: 500px;
}

.sign {
  border: 0;
}

:deep(.sign .el-input__wrapper) {
  box-shadow: none !important;
}

.el-select-dropdown__item {
  text-align: center;
}

.el-row {
  margin-bottom: 20px;
}
.el-col {
  padding: 0 10px;
}
.condition-label {
  min-width: 80px;
  text-align: right;
  margin-right: 10px;
}
.dynamic-condition {
  margin-top: 15px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}


</style>