<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则名称" prop="alarmRuleName">
        <el-input
          v-model="queryParams.alarmRuleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属场景" prop="sceneId">
        <el-select v-model="queryParams.sceneId" placeholder="请选择所属场景" @input="sceneChange" clearable>
          <el-option
            v-for="(scene, index) in scenes"
            :key="index"
            :label="scene.sceneName"
            :value="scene.sceneId"
          ></el-option>
        </el-select>

      </el-form-item>

      <el-form-item label="报警级别" prop="alarmLevelId">
        <el-select v-model="queryParams.alarmLevelId" placeholder="请选择报警级别" clearable>
          <el-option
            v-for="(alarmLevel, index) in alarmLevels"
            :key="index"
            :label="alarmLevel.alarmLevelName"
            :value="alarmLevel.alarmLevelId"
          ></el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="报警类型" prop="alarmTypeId">
        <el-select v-model="queryParams.alarmTypeId" placeholder="请选择报警类型" clearable>
          <el-option
            v-for="(alarmType, index) in alarmTypes"
            :key="index"
            :label="alarmType.alarmTypeName"
            :value="alarmType.alarmTypeId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="ruleDeviceId">
        <el-select v-model="queryParams.ruleDeviceId" placeholder="请选择设备" clearable>
          <el-option
            v-for="(device, index) in devices"
            :key="index"
            :label="device.deviceName"
            :value="device.deviceId"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="联动标识" prop="linkFlag">
        <el-select v-model="queryParams.linkFlag" placeholder="请选择联动标识" clearable>
          <el-option
            v-for="dict in dict.type.hw_alarm_rule_link_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="alarmRuleStatus">
        <el-select v-model="queryParams.alarmRuleStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.hw_alarm_rule_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:alarmRule:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:alarmRule:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:alarmRule:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:alarmRule:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="规则ID" align="center" prop="alarmRuleId"/>
      <el-table-column label="规则名称" align="center" prop="alarmRuleName"/>
      <el-table-column label="所属租户" align="center" prop="tenantName"/>
      <el-table-column label="所属场景" align="center" prop="sceneName"/>
      <el-table-column label="报警级别" align="center" prop="alarmLevelName"/>
      <el-table-column label="报警类型" align="center" prop="alarmTypeName"/>
      <el-table-column label="设备" align="center" prop="ruleDeviceName"/>
      <el-table-column label="触发规则" align="center" prop="triggerExpression"/>
      <el-table-column label="联动标识" align="center" prop="linkFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_alarm_rule_link_flag" :value="scope.row.linkFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="alarmRuleStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_alarm_rule_status" :value="scope.row.alarmRuleStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:alarmRule:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:alarmRule:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报警规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="660px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px" >
        <el-form-item label="规则名称" prop="alarmRuleName">
          <el-input v-model="form.alarmRuleName" placeholder="请输入规则名称" style="width: 240px"/>
        </el-form-item>

        <el-form-item label="所属场景" prop="sceneId">
          <el-select v-model="form.sceneId" placeholder="请选择所属场景" @input="editedSceneChange"
                     :disabled="sceneDisabled" style="width: 240px">
            <el-option
              v-for="(scene, index) in editedScenes"
              :key="index"
              :label="scene.sceneName"
              :value="scene.sceneId"
              :disabled="scene.selectedDisable && scene.selectedDisable == 1"
            ></el-option>
          </el-select>

        </el-form-item>


        <el-form-item label="报警级别" prop="alarmLevelId">
          <el-select v-model="form.alarmLevelId" placeholder="请选择报警级别" style="width: 240px">
            <el-option
              v-for="(alarmLevel, index) in editedAlarmLevels"
              :key="index"
              :label="alarmLevel.alarmLevelName"
              :value="alarmLevel.alarmLevelId"
            ></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="报警类型" prop="alarmTypeId">
          <el-select v-model="form.alarmTypeId" placeholder="请选择报警类型" style="width: 240px">
            <el-option
              v-for="(alarmType, index) in editedAlarmTypes"
              :key="index"
              :label="alarmType.alarmTypeName"
              :value="alarmType.alarmTypeId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="触发时间间隔" prop="triggerTimeFrame">
          <el-input v-model="form.triggerTimeFrame" placeholder="请输入时间（分）" style="width: 240px"/>
        </el-form-item>

        <el-form-item label="告警联系人" prop="phoneNumbers">
          <el-select v-model="form.phoneNumbers" placeholder="请选择告警联系人" style="width: 240px">
            <el-option
              v-for="(i, index) in phoneList"
              :key="index"
              :label="i.nickName +'('+ i.phonenumber+')'"
              :value="i.phonenumber"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="设备" prop="ruleDeviceId">
              <el-select v-model="form.ruleDeviceId" placeholder="请选择设备" :disabled="editedDisabled"
                         @input="editedDeviceChange" style="width: 180px">
                <el-option
                  v-for="(device, index) in editedDevices"
                  :key="index"
                  :label="device.deviceName"
                  :value="device.deviceId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备属性" prop="ruleModeFunctionIdentifier">
              <el-select v-model="form.ruleModeFunctionIdentifier" placeholder="请选择设备属性"
                         :disabled="editedDisabled" style="width: 180px">
                <el-option
                  v-for="(deviceModeFunction, index) in editedDeviceModeAttributes"
                  :key="index"
                  :label="deviceModeFunction.functionName"
                  :value="deviceModeFunction.functionIdentifier"
                ></el-option>
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="触发条件" prop="triggerCondition">
          <el-select v-model="form.triggerCondition" placeholder="请选择触发条件" @input="triggerConditionChange"
                     :disabled="editedDisabled" style="width: 240px">
            <el-option
              v-for="dict in dict.type.hw_alarm_rule_trigger_condition"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="A值" prop="triggerDataA">
              <el-input v-model="form.triggerDataA" placeholder="请输入A值" :disabled="editedDisabled" style="width: 240px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="B值" prop="triggerDataB" v-if="triggerDataBVisible">
              <el-input v-model="form.triggerDataB" placeholder="请输入B值" :disabled="editedDisabled" style="width: 240px"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="状态" prop="alarmRuleStatus">
          <el-radio-group v-model="form.alarmRuleStatus">"
            <el-radio
              v-for="dict in dict.type.hw_alarm_rule_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>

        </el-form-item>


        <el-form-item label="联动标识" prop="linkFlag">
          <el-radio-group v-model="form.linkFlag" @input="linkFlagChange">
            <el-radio
              v-for="dict in dict.type.hw_alarm_rule_link_flag"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>&nbsp;

          <el-button type="primary" @click="handleAddAlarmRuleLink" icon="el-icon-plus" size="mini"
                     v-if="alarmRuleLinkVisible">添加联动设备
          </el-button>

          <el-table :data="alarmRuleLinkData" :row-class-name="rowHwAlarmRuleLinkIndex"
                    ref="hwAlarmRuleLink" v-if="alarmRuleLinkVisible">
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column
              label="联动类型"
              prop="linkType"
              min-width="10%"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.hw_alarm_rule_link_type" :value="scope.row.linkType"/>
              </template>
            </el-table-column>

            <el-table-column
              label="联动设备"
              prop="linkDeviceName"
              min-width="10%"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="联动设备服务"
              prop="linkDeviceModeFunctionName"
              min-width="10%"
              :show-overflow-tooltip="true"
            />

            <el-table-column label="操作" align="center" min-width="10%">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateAlarmRuleLink(scope.row)"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteAlarmRuleLink(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>

          </el-table>

        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改联动设备对话框-->
    <el-dialog :title="alarmRuleLinkTitle" :visible.sync="alarmRuleLinkOpen" width="500px" append-to-body>
      <el-form ref="alarmRuleLinkForm" :model="alarmRuleLinkForm" :rules="alarmRuleLinkRules" label-width="80px">

        <el-form-item label="联动类型" prop="linkType">
          <el-select v-model="alarmRuleLinkForm.linkType" placeholder="请选择联动类型">
            <el-option
              v-for="dict in dict.type.hw_alarm_rule_link_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>

        </el-form-item>

        <el-row>
          <el-col span="12">
            <el-form-item label="设备" prop="linkDeviceId">
              <el-select v-model="alarmRuleLinkForm.linkDeviceId" placeholder="请选择设备"
                         @input="editedLinkDeviceChange">
                <el-option
                  v-for="(device, index) in editedDevices"
                  :key="index"
                  :label="device.deviceName"
                  :value="device.deviceId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col span="12">
            <el-form-item label="设备服务" prop="linkDeviceFunctionId">
              <el-select v-model="alarmRuleLinkForm.linkDeviceFunctionId" placeholder="请选择设备服务"
                         @input="editedLinkDeviceModeServiceChange">
                <el-option
                  v-for="(deviceModeFunction, index) in editedDeviceModeServices"
                  :key="index"
                  :label="deviceModeFunction.functionName"
                  :value="deviceModeFunction.modeFunctionId"
                ></el-option>
              </el-select>

            </el-form-item>
          </el-col>

        </el-row>


        <!--el-form-item
          v-for="(parameter,index) in modeFunctionParameters"
          :label="parameter.parameterName"
          :key="parameter.parameterIdentifier"
          :prop="'parameters'+index"
        >
          <el-input v-model="alarmRuleLinkForm.parameters" placeholder="请输入内容"/>
        </el-form-item-->


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRuleLinkForm">确 定</el-button>
        <el-button @click="cancelAlarmRuleLink">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listAlarmRule, getAlarmRule, delAlarmRule, addAlarmRule, updateAlarmRule,
  getScenes, getEditedScenes, getSelectListBySceneId, getDeviceModeByDeviceId, getModeFunctionParametersByModeFunctionId
} from "@/api/business/alarmRule";
import {addDeviceModeFunction} from "@/api/business/deviceModeFunction";
import {listUser} from "../../../api/system/user";

export default {
  name: "AlarmRule",
  dicts: ['hw_alarm_rule_type', 'hw_alarm_rule_link_flag', 'hw_alarm_rule_status', 'hw_alarm_rule_push_flag', 'hw_alarm_rule_trigger_condition', 'hw_alarm_rule_link_type'],
  data() {
    return {
      phoneList: [],
      FUNCTION_MODE_ATTRIBUTE: "1", //设备模型属性
      FUNCTION_MODE_SERVICE: "2",//设备模型服务
      DATA_MORE_THAN_A_AND_LESS_THAN_B: 3,//大于A且小于B
      DATA_LESS_THAN_A_OR_MORE_THAN_B: 4,//小于A或大于B
      LINK_FLAG_YES: "1",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedHwAlarmRuleDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报警规则表格数据
      alarmRuleList: [],
      // 报警规则详情表格数据
      hwAlarmRuleLinkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmRuleName: null,
        tenantId: null,
        sceneId: null,
        languageCode: null,
        alarmLevelId: null,
        alarmTypeId: null,
        ruleType: null,
        ruleDeviceId: null,
        ruleFunctionTotal: null,
        linkFlag: null,
        alarmRuleStatus: null,
        alarmPushFlag: null,
        alarmPushContent: null,
        alarmRecoverContent: null,
        alarmRuleField: null
      },

      triggerDataBVisible: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        alarmRuleName: [
          {required: true, message: "规则名称不能为空", trigger: "blur"}
        ],
        sceneId: [
          {required: true, message: "所属场景不能为空", trigger: "change"}
        ],
        alarmLevelId: [
          {required: true, message: "报警级别不能为空", trigger: "change"}
        ],
        alarmTypeId: [
          {required: true, message: "报警类型不能为空", trigger: "change"}
        ],
        ruleDeviceId: [
          {
            required: true,
            message: "设备不能为空",
            trigger: "change"
          }
        ],
        ruleModeFunctionIdentifier: [
          {
            required: true,
            message: "设备属性不能为空",
            trigger: "change"
          }
        ],
        triggerCondition: [
          {
            required: true,
            message: "表达式不能为空",
            trigger: "change"
          }
        ],
        triggerDataA: [
          {
            required: true,
            message: "A值不能为空",
            trigger: "blur"
          },
          {
            pattern: /^(-)?(([0-9])|([1-9]([0-9]+)))(\.[0-9]+)?$/,
            message: "请输入正确的数字",
            trigger: "blur"
          }

        ],
        triggerDataB: [
          {
            required: true,
            message: "B值不能为空",
            trigger: "blur"
          },
          {
            pattern: /^(-)?(([0-9])|([1-9]([0-9]+)))(\.[0-9]+)?$/,
            message: "请输入正确的数字",
            trigger: "blur"
          }
        ],
        linkFlag: [
          {required: true, message: "联动标识不能为空", trigger: "change"}
        ],
        alarmRuleStatus: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ],
      },

      scenes: [],
      alarmLevels: [],
      alarmTypes: [],
      devices: [],

      alarmRuleFlag: "1",
      editedScenes: [],
      editedDisabled: true,
      sceneDisabled: true,
      editedAlarmLevels: [],
      editedAlarmTypes: [],
      editedDevices: [],
      editedDeviceModeAttributes: [],
      editedDeviceModeServices: [],

      alarmRuleLinkVisible: false,
      alarmRuleLinkData: [],
      alarmRuleLinkTitle: "",
      alarmRuleLinkOpen: false,
      alarmRuleLinkForm: {},
      modeFunctionParameters: [],
      alarmRuleLinkRules: {
        linkType: [
          {required: true, message: "联动类型不能为空", trigger: "change"}
        ],
        linkDeviceId: [
          {required: true, message: "设备不能为空", trigger: "change"},
        ],
        linkDeviceFunctionId: [
          {required: true, message: "设备服务不能为空", trigger: "change"},
        ],
      },

    };
  },
  created() {
    this.getList();
    this.getScenes();
    this.getPhoneList()
  },
  methods: {
    getPhoneList() {
      listUser({
        pageNum: 1,
        pageSize: 10000000
      }).then(response => {
          this.phoneList = response.rows.filter(v => !!v.phonenumber);
        }
      );
    },
    /** 查询报警规则列表 */
    getList() {
      this.loading = true;
      listAlarmRule(this.queryParams).then(response => {
        this.alarmRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.editedDeviceModeAttributes = [];
      this.editedDevices = [];
      this.editedAlarmTypes = [];
      this.editedAlarmLevels = [];
      this.alarmRuleLinkData = [];
      this.form = {
        alarmRuleId: null,
        alarmRuleName: null,
        tenantId: null,
        sceneId: null,
        languageCode: null,
        alarmLevelId: null,
        alarmTypeId: null,
        ruleType: '2',
        ruleDeviceId: null,
        ruleFunctionTotal: null,
        linkFlag: "0",
        alarmRuleStatus: "1",
        alarmPushFlag: "0",
        alarmPushContent: null,
        alarmRecoverContent: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        alarmRuleField: null,
        ruleModeFunctionIdentifier: null,
        triggerCondition: '1',
        triggerDataA: null,
        triggerDataB: null,
      };
      this.hwAlarmRuleDetailList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.alarmRuleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editedDisabled = false;
      this.sceneDisabled = false;
      this.reset();
      this.getEditedScenes();
      this.open = true;
      this.title = "添加报警规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.sceneDisabled = true;
      this.getEditedScenes();
      const alarmRuleId = row.alarmRuleId || this.ids

      getAlarmRule(alarmRuleId).then(response => {
        this.form = response.data;
        this.editedDisabled = response.data.alarmInfoFlag === "1";
        this.getEditedSelectListBySceneId(this.form.sceneId);
        this.getDeviceModeByDeviceId(this.form.ruleDeviceId);
        this.triggerDataBVisibleJudge(this.form.triggerCondition);
        this.alarmRuleLinkData = response.data.hwAlarmRuleLinkList;
        this.alarmRuleLinkVisible = response.data.linkFlag === this.LINK_FLAG_YES;
        this.open = true;
        this.title = "修改报警规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.linkFlag == this.LINK_FLAG_YES &&
            (this.alarmRuleLinkData == null || this.alarmRuleLinkData.length <= 0)) {
            this.$modal.msgWarning("请添加联动设备");
            return;
          }
          this.form.hwAlarmRuleLinkList = this.alarmRuleLinkData;
          this.form.ruleFunctionTotal = 1;//暂时写1，后续支持配置多个详情时再修改
          if (this.form.alarmRuleId != null) {
            updateAlarmRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAlarmRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const alarmRuleIds = row.alarmRuleId || this.ids;
      this.$modal.confirm('是否确认删除报警规则ID为"' + alarmRuleIds + '"的数据项？').then(function () {
        return delAlarmRule(alarmRuleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 报警规则详情序号 */
    rowHwAlarmRuleLinkIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 报警规则详情添加按钮操作 */
    // handleAddHwAlarmRuleDetail() {
    //   let obj = {};
    //   obj.modeFunctionId = "";
    //   obj.ruleDetailOrder = "";
    //   obj.triggerCondition = "";
    //   obj.triggerDataA = "";
    //   obj.triggerDataB = "";
    //   obj.triggerDeadzone = "";
    //   obj.triggerNumber = "";
    //   obj.triggerTimeFrame = "";
    //   this.hwAlarmRuleDetailList.push(obj);
    // },
    // /** 报警规则详情删除按钮操作 */
    // handleDeleteHwAlarmRuleDetail() {
    //   if (this.checkedHwAlarmRuleDetail.length == 0) {
    //     this.$modal.msgError("请先选择要删除的报警规则详情数据");
    //   } else {
    //     const hwAlarmRuleDetailList = this.hwAlarmRuleDetailList;
    //     const checkedHwAlarmRuleDetail = this.checkedHwAlarmRuleDetail;
    //     this.hwAlarmRuleDetailList = hwAlarmRuleDetailList.filter(function (item) {
    //       return checkedHwAlarmRuleDetail.indexOf(item.index) == -1
    //     });
    //   }
    // },
    // /** 复选框选中数据 */
    // handleHwAlarmRuleDetailSelectionChange(selection) {
    //   this.checkedHwAlarmRuleDetail = selection.map(item => item.index)
    // },

    /** 导出按钮操作 */
    handleExport() {
      this.download('business/alarmRule/export', {
        ...this.queryParams
      }, `alarmRule_${new Date().getTime()}.xlsx`)
    },

    getScenes() {
      getScenes().then(response => {
        this.scenes = response.data;
      });
    },

    sceneChange(sceneId) {
      this.devices = [];
      this.alarmTypes = [];
      this.alarmLevels = [];
      this.queryParams.alarmTypeId = null;
      this.queryParams.alarmLevelId = null;
      this.queryParams.ruleDeviceId = null;
      this.getSelectListBySceneId(sceneId);
    },

    getSelectListBySceneId(sceneId) {
      if (sceneId != null && sceneId !== '') {
        getSelectListBySceneId(sceneId).then(response => {
          this.devices = response.data["devices"];
          this.alarmTypes = response.data["alarmTypes"];
          this.alarmLevels = response.data["alarmLevels"];
        })
      }
    },

    getEditedScenes() {
      getEditedScenes().then(response => {
        this.editedScenes = response.data;
      });
    },

    getEditedSelectListBySceneId(sceneId) {
      getSelectListBySceneId(sceneId).then(response => {
        this.editedDevices = response.data["devices"];
        this.editedAlarmTypes = response.data["alarmTypes"];
        this.editedAlarmLevels = response.data["alarmLevels"];
      })
    },

    editedSceneChange(sceneId) {
      this.editedDevices = [];
      this.editedAlarmTypes = [];
      this.editedAlarmLevels = [];
      this.editedDeviceModeAttributes = [];
      this.form.alarmTypeId = null;
      this.form.alarmLevelId = null;
      this.form.ruleDeviceId = null;
      this.form.ruleModeFunctionIdentifier = null;
      this.alarmRuleLinkData = [];
      this.alarmRuleLinkVisible = this.form.linkFlag === "1";
      this.getEditedSelectListBySceneId(sceneId);
    },

    getDeviceModeByDeviceId(deviceId) {
      getDeviceModeByDeviceId(deviceId).then(response => {
        const hwDeviceModeFunctionList = response.data["hwDeviceModeFunctionList"];
        if (hwDeviceModeFunctionList != null) {
          this.editedDeviceModeAttributes = hwDeviceModeFunctionList.filter(item => item.functionMode == this.FUNCTION_MODE_ATTRIBUTE)
        }
      })
    },

    editedDeviceChange(deviceId) {
      this.form.ruleModeFunctionIdentifier = null;
      this.getDeviceModeByDeviceId(deviceId);
    },

    triggerDataBVisibleJudge(triggerCondition) {
      if (triggerCondition == this.DATA_MORE_THAN_A_AND_LESS_THAN_B
        || triggerCondition == this.DATA_LESS_THAN_A_OR_MORE_THAN_B) {
        this.triggerDataBVisible = true;
      } else {
        this.triggerDataBVisible = false;
      }
    },

    triggerConditionChange(triggerCondition) {
      this.triggerDataBVisibleJudge(triggerCondition);
    },

    getDeviceModeServicesByDeviceId(deviceId) {
      getDeviceModeByDeviceId(deviceId).then(response => {
        const hwDeviceModeFunctionList = response.data["hwDeviceModeFunctionList"];
        if (hwDeviceModeFunctionList != null) {
          this.editedDeviceModeServices = hwDeviceModeFunctionList.filter(item => item.functionMode == this.FUNCTION_MODE_SERVICE)
        }
      })
    },

    editedLinkDeviceChange(deviceId) {
      this.alarmRuleLinkForm.linkDeviceFunctionId = null;
      const selectedOption = this.editedDevices.find(option => option.deviceId === deviceId);
      this.alarmRuleLinkForm.linkDeviceName = selectedOption.deviceName;
      this.getDeviceModeServicesByDeviceId(deviceId);
    },

    editedLinkDeviceModeServiceChange(modeFunctionId) {
      const selectedOption = this.editedDeviceModeServices.find(option => option.modeFunctionId === modeFunctionId);
      this.alarmRuleLinkForm.linkDeviceModeFunctionName = selectedOption.functionName;
      this.alarmRuleLinkForm.linkDeviceFunctionIdentifier = selectedOption.functionIdentifier;

      // getModeFunctionParametersByModeFunctionId(modeFunctionId).then(response => {
      //   const modeFunctionParameters = response.data;
      //   if(modeFunctionParameters!=null){
      //     this.modeFunctionParameters = modeFunctionParameters[1];
      //   }
      // })

    },


    // 报警规则详情表单重置
    resetAlarmRuleDetail() {
      this.alarmRuleDetailForm = {
        modeFunctionId: null,
        modeFunctionIdentifier: null,
        ruleDetailOrder: null,
        triggerCondition: null,
        triggerDataA: null,
        triggerDataB: null,
        triggerDeadzone: null,
        triggerNumber: null,
        triggerTimeFrame: null,
      };
      //this.resetForm("inputParameterForm");
    },

    linkFlagChange(linkFlag) {
      this.alarmRuleLinkVisible = linkFlag === "1" && this.form.sceneId != null;
    },

    // 报警规则联动设备表单重置
    resetAlarmRuleLink() {
      this.alarmRuleLinkForm = {
        alarmRuleType: '1',
        linkType: null,
        linkDeviceId: null,
        linkDeviceFunctionId: null,
        linkDeviceFunctionIdentifier: null,
        linkDeviceFunctionData: null,
        linkDeviceName: null,
        linkDeviceModeFunctionName: null
      };
      //this.resetForm("inputParameterForm");
    },

    handleAddAlarmRuleLink() {
      this.resetAlarmRuleLink();
      this.alarmRuleLinkOpen = true;
      this.alarmRuleLinkTitle = "添加联动设备";
    },

    handleUpdateAlarmRuleLink(row) {
      this.alarmRuleLinkIndex = this.alarmRuleLinkData.indexOf(row);
      const linkDeviceId = row.linkDeviceId;
      this.getDeviceModeServicesByDeviceId(linkDeviceId);
      this.alarmRuleLinkForm = JSON.parse(JSON.stringify(row));
      this.alarmRuleLinkOpen = true;
      this.alarmRuleLinkTitle = "修改联动设备";
    },

    handleDeleteAlarmRuleLink(row) {
      // this.reset();
      // alert(JSON.stringify(this.alarmRuleLinkData));
      this.alarmRuleLinkData.splice(this.alarmRuleLinkData.indexOf(row), 1);
    },

    submitRuleLinkForm() {
      this.$refs['alarmRuleLinkForm'].validate(valid => {
        if (valid) {
          /** 联动设备添加后在list中添加 */
          if (this.deviceModeId && this.deviceModeId !== '') {
            let modeFunctionId = this.form.modeFunctionId;
            this.form.deviceModeId = this.deviceModeId;
            if (modeFunctionId !== undefined && modeFunctionId != null) {
              let attributeDataIndex = this.attributeDataIndex;
              this.doUpdateDeviceModeFunction();
            } else {
              addDeviceModeFunction(this.form).then(res => {
                this.$modal.msgSuccess(res.msg);
                if (res.code === 200) {
                  this.open = false;
                  this.form.modeFunctionId = res.data;
                  this.pushData();
                }
              });
            }
          } else {
            this.alarmRuleLinkOpen = false;
            this.pushData();
          }
        }
      })
    },

    pushData() {
      let alarmRuleLinkIndex = this.alarmRuleLinkIndex;
      if (alarmRuleLinkIndex > -1) {
        this.alarmRuleLinkIndex = -1;
        this.alarmRuleLinkData.splice(alarmRuleLinkIndex, 1, this.alarmRuleLinkForm);
      } else {
        this.alarmRuleLinkData.push(this.alarmRuleLinkForm)
      }
    },

    // 联动设备弹窗取消按钮
    cancelAlarmRuleLink() {
      this.alarmRuleLinkOpen = false;
      this.resetAlarmRuleLink();
    },

  }
};
</script>
