<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-row>
        <el-col :span="4">
          <el-form-item label="中台设备ID" prop="deviceUuid">
            <el-input
              v-model="queryParams.deviceUuid"
              placeholder="请输入中台设备ID"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              v-model="queryParams.deviceName"
              placeholder="请输入设备名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="参数编码" prop="paramCode">
            <el-input
              v-model="queryParams.paramCode"
              placeholder="请输入参数编码"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="参数名称" prop="paramName">
            <el-input
              v-model="queryParams.paramName"
              placeholder="请输入参数名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item class="childTextAlignCenter">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button type="info" plain icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Delete"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="deviceParamsTable" v-loading="loading" :data="alertList">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="中台设备ID" align="center" prop="deviceUuid" />
      <el-table-column label="设备名称" align="center" prop="deviceName" :width="120"/>
      <el-table-column label="参数名称" align="center" prop="paramName" :width="120"/>
      <el-table-column label="参数类型" align="center" prop="paramType" :width="120">
        <template #default="scope">
          <dict-tag :options="dc_param_value_type" :value="scope.row.paramType"/>
        </template>
      </el-table-column>
      <el-table-column label="参数编码" align="center" prop="paramCode" />
      <el-table-column label="是否告警" align="center" prop="enabled" :width="120">
        <template #default="scope">
          <el-switch v-model="scope.row.enabled" :active-value="1" :inactive-value="0" @change="changeEnabled(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="Delete"
            @click="handlePolicy(scope.row)"
          >维护告警策略</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备告警对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="alertRef" :model="form" :rules="rules" label-width="80px">
        <el-row>  
          <el-col :span="12">
            <el-form-item label="告警设备" prop="deviceUuid">
              <el-select v-model="form.deviceUuid" filterable placeholder="请选择参数" clearable @change="getParamsList">
                <el-option
                  v-for="item in deviceList"
                  :key="item.uuid"
                  :label="item.deviceName"
                  :value="item.uuid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="告警参数" prop="paramCode">
              <el-select v-model="form.paramCode" filterable placeholder="请选择参数" clearable @change="setParamsType">
                <el-option
                  v-for="item in paramsList"
                  :key="item.paramCode"
                  :label="item.paramName"
                  :value="item.paramCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="告警参数类型" v-show="false" prop="paramCode">
              <el-input v-model="form.paramType"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改参数值状态策略对话框 -->
    <el-dialog :title="titlePolicy" v-model="openPolicy" :width="dialogWidth" append-to-body>
      <el-form ref="policyRef" :model="formPolicy" :rules="rulesPolicy" label-width="120px">
        <el-row>  
          <el-col :span="12" v-show="boolValueVisiable">
            <el-form-item label="告警值" prop="boolValue">
              <!-- <el-input v-model="formPolicy.boolValue" placeholder="请输入开始值" /> -->
              <el-select v-model="formPolicy.boolValue" placeholder="请选择是否告警">
                <el-option
                  v-for="item in alert_value"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="methodIdsVisiable">
            <el-form-item label="告警方式" prop="methodIds">
              <el-select v-model="formPolicy.methodIds" placeholder="请选择告警方式">
                <el-option
                  v-for="item in methodList"
                  :key="item.id"
                  :label="item.methodName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="sortIdVisiable">
            <el-form-item label="排序"  prop="sortId">
              <el-input-number v-model="formPolicy.sortId" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="statusValueVisiable">
            <el-form-item label="状态值" prop="statusValue">
              <el-select v-model="formPolicy.statusType" placeholder="请选择状态值">
                <el-option
                  v-for="item in status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="statusTypeVisiable">
            <el-form-item label="状态类型" prop="statusType">
              <el-select v-model="formPolicy.statusType" placeholder="请选择状态类型">
                <el-option
                  v-for="item in status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 10px;" v-show="tableVisiable">
          <el-col>
            <h3>告警逻辑</h3>
          </el-col>
        </el-row>
        <el-row v-show="tableVisiable">
          <el-col>
              <el-table ref="policyTable" v-loading="loading" :data="modelList" :row-key="getRowKey" @selection-change="handleSelectionChange">
                <el-table-column type="selection" reserve-selection="true" width="55" align="center" />
                <el-table-column label="名称" align="center" prop="name"/>
                <el-table-column label="符号" align="center" prop="code" :width="120"/>
                <el-table-column label="运算符" align="center" prop="operator" :width="120">
                  <template #default="scope">
                    <dict-tag :options="operator_sign" :value="scope.row.operator"/>
                  </template>
                </el-table-column>
                <el-table-column label="限值" align="center" prop="value">
                  <template #default="scope">
                    <el-form-item :class="{ 'is-error': isInvalid(scope.row.value,scope.row),'is-error-value': colorValue[scope.row.sort]}" label-width="0px">
                      <el-input v-model="scope.row.value" @change="handleValueChange(scope.row)"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="级别" align="center" prop="level" />
                <el-table-column label="排序" align="center" prop="sort"/>
                <el-table-column label="告警方式" align="center" prop="methodIds" >
                  <template #default="scope">
                    <el-form-item :class="{'is-error': isInvalid(scope.row.methodIds,scope.row)}" label-width="0px" >
                      <el-select v-model="scope.row.methodIds" multiple @change="methodIdsChange" placeholder="请选择告警方式">
                        <el-option
                          v-for="item in methodList"
                          :key="item.id"
                          :label="item.methodName"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="状态值" align="center" prop="statusValue">
                  <template #default="scope">
                    <el-select v-model="scope.row.statusValue" placeholder="请选择状态类型">
                      <el-option
                        v-for="item in statusValueSelects"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="状态类型" align="center" prop="statusType">
                  <template #default="scope">
                    <el-select v-model="scope.row.statusType" placeholder="请选择状态类型">
                      <el-option
                        v-for="item in statusSelects"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column> -->
              </el-table>
          </el-col>
        </el-row>
            
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormPolicy">确 定</el-button>
          <el-button @click="cancelPolicy">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" > 
  @import "@/assets/styles/self-defined.scss";
</style>
<script setup name="Alert">
import { getDeviceParamsAlertInfo,delAlert, addAlert, updateAlert } from "@/api/model/alert";
import { listDeviceNoPage } from "@/api/model/device";
import { listMethod } from "@/api/model/method";
import { listModel } from "@/api/model/alertmodel";
import { ElMessageBox } from 'element-plus';
import {listPolicyInfo,updatePolicy,updatePolicyBatch,addPolicy,addPolicyBatch,listAlertParamSelect } from "@/api/model/policy";
const { proxy } = getCurrentInstance();
const router = useRouter();
const { operator_sign,dc_param_value_type } = proxy.useDict('operator_sign','dc_param_value_type');
const alertList = ref([]);
const open = ref(false);
const openPolicy = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const deviceList = ref([]);
const paramsList = ref([]);
const methodList = ref([]);
const modelList = ref([]);
const selectedRows = ref([]);
const deletePolicyRows = ref([]);
const oldPolicyRows = ref([]);
const addPolicyRows = ref([]);
const boolValueVisiable = ref(false);
const statusValueVisiable = ref(false);
const statusTypeVisiable = ref(false);
const sortIdVisiable = ref(false);
const methodIdsVisiable = ref(false);
const policyModelVisiable = ref(false);
const policyEnabledVisiable = ref(false);
const policyParams = ref([]);
const policyAlertId = ref("");
const policyDeviceUuid = ref("");
const paramTypeValue = ref("");
const logicCode = ref("");
const rowPolicySelected = ref([]);
const colorValue = ref({});
const tableVisiable = ref(false);
const dialogWidth = ref('1600px');
const alert_value = ref([
  {label: '1', value: true, elTagType: 'default', elTagClass: null}, 
  {label: '0', value: false, elTagType: 'default', elTagClass: null}
]);

const statusSelects = ref([]);
const statusValueSelects = ref([]);
const data = reactive({
  form: {},
  formPolicy: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceUuid: null,
    paramCode: null,
    note: null
  },
  queryParamsDevice: {
    deviceUuid: null,
  },
  queryParamsParam: {
    deviceUuid: null,
    paramCode: null,
  },
  queryParamsPolicy:{
    pageNum: 1,
    pageSize: 10,
    boolValue: null,
    endValue: null,
    alertId: null,
    statusValue: null,
    statusType: null,
    deviceId: null,
    sortId: null,
    methodIds: null
  },
  queryPolicy:{
    alertId: null,
  },
  rules: {
    deviceUuid: [
      { required: true, message: "中台设备UUID不能为空", trigger: "blur" }
    ],
    paramCode: [
      { required: true, message: "参数编码不能为空", trigger: "blur" }
    ],
  },
  rulesPolicy: {
    deviceUuid: [
      { required: true, message: "中台设备UUID不能为空", trigger: "blur" }
    ],
    paramCode: [
      { required: true, message: "参数编码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParamsDevice, queryParamsParam, queryParams, form, rules,queryParamsPolicy,queryPolicy, formPolicy, rulesPolicy } = toRefs(data);

/** 查询设备告警列表 */
function getList() {
  loading.value = true;
  getDeviceParamsAlertInfo(queryParams.value).then(response => {
    alertList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    tentantId: null,
    version: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deptId: null,
    userId: null,
    deleteBy: null,
    deleteTime: null,
    id: null,
    boolValue: null,
    alertId: null,
    statusValue: null,
    statusType: null,
    deviceId: null,
    sortId: null,
    sort: null,
    methodIds: null,
    level:null,
    operator: null,
    operator_sign: null,
    enabled: null,
  };
  proxy.resetForm("alertRef");
}

// 表单重置
function resetPolicy() {
  formPolicy.value = {
    tentantId: null,
    version: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deptId: null,
    userId: null,
    deleteBy: null,
    deleteTime: null,
    id: null,
    boolValue: null,
    alertId: null,
    statusValue: null,
    statusType: null,
    deviceId: null,
    sortId: null,
    sort: null,
    methodIds: null,
    level:null,
    operator: null,
    operator_sign: null,
    enabled:null,
  };
  proxy.resetForm("policyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selection.forEach(item=>{
    if(!rowPolicySelected.value.includes(item)){
      handleValueChange(item);
    }
  })
  rowPolicySelected.value = selection;
  
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getDeviceList();
  open.value = true;
  title.value = "添加设备告警";
}

/** 维护告警策略 */
function handlePolicy(row) {
  resetPolicy();
  selectedRows.value=[];
  deletePolicyRows.value=[];
  addPolicyRows.value=[];
  deletePolicyRows.value=[];
  logicCode.value = row.logicCode;
  formPolicy.value.enabled = row.enabled;
  if(row.logicCode=='A'){
    dialogWidth.value = '800px';
    getModelListSwitch(row);
    boolValueVisiable.value=true;
    policyModelVisiable.value=false;
    statusValueVisiable.value=false;
    statusTypeVisiable.value=false;
    sortIdVisiable.value=false;
    methodIdsVisiable.value=true;
    tableVisiable.value=false;
  }else if(row.logicCode == 'B'){
    dialogWidth.value = '1600px';
    getModelList(row);
    policyModelVisiable.value=true;
    boolValueVisiable.value=false;
    statusValueVisiable.value=false;
    statusTypeVisiable.value=false;
    sortIdVisiable.value=false;
    methodIdsVisiable.value=false;
    tableVisiable.value=true;
  }else if(row.logicCode == 'C'){
    ElMessageBox.alert('目前该告警逻辑没有实现', '提示', {
      confirmButtonText: '确定',
      center: true,
    })
    return;
  }else{
    ElMessageBox.alert('请确保已创建有效告警逻辑', '提示', {
      confirmButtonText: '确定',
      center: true,
    })
    return;
  }
  getMethodList();
  queryParamsPolicy.value.alertId = row.id;
  policyAlertId.value = row.id;
  policyDeviceUuid.value = row.deviceUuid;
  paramTypeValue.value = row.paramType;
  openPolicy.value = true;
  title.value = "维护告警策略";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["alertRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAlert(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAlert(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete() {
  const rows = proxy.$refs.deviceParamsTable.getSelectionRows();
  let names = "";
  let _ids = [];
  rows.forEach(item=>{
    _ids.push(item.id);
    if(names == ""){
      names = item.deviceName + item.paramName;
    }else{
      names = names + "," + item.deviceName + item.paramName;
    }
  })
  proxy.$modal.confirm('是否确认删除设备参数名称为"' + names + '"的数据项？').then(function() {
    return delAlert(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 删除按钮操作 */
function handleDeleteRow(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备告警编号为"' + _ids + '"的数据项？').then(function() {
    return delAlert(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('model/alert/export', {
    ...queryParams.value
  }, `alert_${new Date().getTime()}.xlsx`)
}

function getDeviceList(){
  loading.value = false;
  listDeviceNoPage(queryParamsDevice.value).then(response => {
    deviceList.value = response.data;
    loading.value = false;
  });
}

function getParamsList(deviceUuid){
  loading.value = true;
  queryParamsParam.value.deviceUuid = deviceUuid;
  listAlertParamSelect(queryParamsParam.value).then(response => {
    paramsList.value = response.data;
    loading.value = false;
  });
}

function getMethodList(){
  listMethod().then(response => {
    methodList.value = response.rows;
  });
}

//提交到策略信息表
function submitFormPolicy() {
  proxy.$refs["policyRef"].validate(valid => {
    if (valid) {
      //根据标志值来判断是否是修改操作
      if (formPolicy.value.id != null) {
        //根据参数类型区分
        if(logicCode.value == 'B' ){
          if(!judgeIfRightValue()){
            ElMessageBox.alert('请确认目前已勾选的告警策略配置是否合理', '提示', {
              confirmButtonText: '确定',
              center: true,
            })
            return;
          };
          mapFormTableUpdate();
          computeDelPolicy();
          computeAddPolicy();
          updatePolicyBatch(policyParams.value,deletePolicyRows.value,addPolicyRows.value,policyDeviceUuid.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            openPolicy.value = false;
            getList();
          });
        }else if(logicCode.value == 'A'){
          updatePolicy(formPolicy.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            openPolicy.value = false;
            getList();
          });
        }
      } else {
        //根据参数类型区分
        if(logicCode.value == 'B' ){
          if(!judgeIfRightValue()){
            ElMessageBox.alert('请确认目前已勾选的告警策略配置是否正确', '提示', {
              confirmButtonText: '确定',
              center: true,
            })
            return;
          };
          mapFormTable();
          addPolicyBatch(policyParams.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            openPolicy.value = false;
            getList();
          });
        }else if(logicCode.value == 'A'){
          addPolicy(formPolicy.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            openPolicy.value = false;
            getList();
          });
        }
      }
    }
  });
}

function cancelPolicy() {
  openPolicy.value = false;
  resetPolicy();
}

//开关量初始化策略表单
function getModelListSwitch(row){
  queryPolicy.value.alertId = row.id;
  listPolicyInfo(queryPolicy.value).then(response=>{
    //修改界面初始化
    if(response.data && response.data.length>0){
      formPolicy.value.statusValue = response.data[0].statusValue;
      formPolicy.value.statusType = response.data[0].statusType;
      formPolicy.value.methodIds = response.data[0].methodIds?.split(',').map(Number);
      formPolicy.value.boolValue = response.data[0].boolValue;
      formPolicy.value.alertId = row.id;
      formPolicy.value.deviceId = row.deviceUuid;
      formPolicy.value.id = response.data[0].id;
    //新增界面初始化
    }else{
      formPolicy.value.alertId = row.id;
      formPolicy.value.deviceId = row.deviceUuid;
    }
  });
}


//非开关量初始化策略表单
function getModelList(row){
  queryPolicy.value.alertId = row.id;
  queryPolicy.value.flagEnabled = true;
  listModel().then(response => {
    modelList.value = response.rows;
    formPolicy.value.alertId = row.id;
    formPolicy.value.deviceId = row.deviceUuid;
    proxy.$refs.policyTable.clearSelection();
    listPolicyInfo(queryPolicy.value).then(responsePolicy=>{
      //修改界面初始化
      if(responsePolicy.data && responsePolicy.data.length>0){
        oldPolicyRows.value = responsePolicy.data;
        formPolicy.value.alertId = responsePolicy.data[0].alertId;
        formPolicy.value.deviceId = responsePolicy.data[0].deviceId;
        formPolicy.value.id = responsePolicy.data[0].id;
        modelList.value.map(element=>{
          responsePolicy.data.forEach(item=>{
            if(item.alertModelId == element.id){
              // policyDeviceUuid.value = item.deviceId;
              // policyAlertId.value = item.alertId;
              if(paramTypeValue.value == '3'){
                element.value = item.floatValue;
              }else if(paramTypeValue.value == '2'){
                element.value = item.stringValue;
              }else if(paramTypeValue.value == '1'){
                element.value = item.intValue;
              }
              element.level = item.level;
              element.name = item.name;
              element.policyId = item.id;
              element.statusValue = item.statusValue;
              element.statusType = item.statusType;
              element.methodIds = item.methodIds?.split(',').map(Number);
              element.operator = item.operator;
              element.sort = item.sortId;
              element.id = item.alertModelId;
              proxy.$refs.policyTable.toggleRowSelection(element,true);
              return element;
            }
          })
        })
      }
    });
  });
  
}

//新增表单映射
function mapFormTable(){
  const policyTableRows = proxy.$refs.policyTable.getSelectionRows();
  policyParams.value=[];
  policyTableRows.forEach(item=>{
    let policyParam = {};
    policyParam.deviceId = policyDeviceUuid.value;
    policyParam.alertId = policyAlertId.value;
    if(paramTypeValue.value == '3'){
      policyParam.floatValue = item.value;
    }else if(paramTypeValue.value == '2'){
      policyParam.stringValue = item.value;
    }else if(paramTypeValue.value == '1'){
      policyParam.intValue = item.value;
    }
    policyParam.level = item.level;
    policyParam.alertModelId = item.id;
    policyParam.name = item.name;
    policyParam.statusValue = item.statusValue;
    policyParam.statusType = item.statusType;
    policyParam.methodIds = item.methodIds?.join(',');
    policyParam.operator = item.operator;
    policyParam.sortId = item.sort;
    policyParams.value.push(policyParam);
  })
}

//修改表单映射
function mapFormTableUpdate(){
  const policyTableRows = proxy.$refs.policyTable.getSelectionRows();
  policyParams.value=[];
  policyTableRows.forEach(item=>{
    let policyParam = {};
    policyParam.id = item.policyId;
    policyParam.deviceId = policyDeviceUuid.value;
    policyParam.alertId = item.alertId;
    if(paramTypeValue.value == '3'){
      policyParam.floatValue = item.value;
    }else if(paramTypeValue.value == '2'){
      policyParam.stringValue = item.value;
    }else if(paramTypeValue.value == '1'){
      policyParam.intValue = item.value;
    }
    policyParam.level = item.level;
    policyParam.alertModelId = item.id;
    policyParam.name = item.name;
    policyParam.statusValue = item.statusValue;
    policyParam.statusType = item.statusType;
    policyParam.methodIds = item.methodIds?.join(',');
    policyParam.operator = item.operator;
    policyParam.sortId = item.sort;
    policyParams.value.push(policyParam);
  })
}

function getRowKey(row){
  // 返回行的唯一标识符
  // 这里使用 id 作为唯一标识符，你可以根据实际情况进行修改
  return row.id;
}


function computeDelPolicy() {
  const newSeletedRows = proxy.$refs.policyTable.getSelectionRows();
  oldPolicyRows.value.forEach(item=>{
    let flag = false;
    newSeletedRows.forEach(element=>{
      if(item.id == element.id){
        flag = true;
      }
    })
    if(!flag){
      policyParams.value = policyParams.value.filter(element=>{
        return item.id === element.id
      })
      deletePolicyRows.value.push(item);
    }
  })
}

function computeAddPolicy() {
  const newSeletedRows = proxy.$refs.policyTable.getSelectionRows();
  newSeletedRows.forEach(item=>{
    let flag = false;
    oldPolicyRows.value.forEach(element=>{
      if(item.id == element.id){
        flag = true;
      }
    })
    if(!flag){
      policyParams.value = policyParams.value.filter(element=>{
        return item.id !== element.id;
      })
      //为了新增不能传id给后台
      let policyParam = {};
      policyParam.deviceId = policyDeviceUuid.value;
      policyParam.alertId = policyAlertId.value;
      if(paramTypeValue.value == '3'){
        policyParam.floatValue = item.value;
      }else if(paramTypeValue.value == '2'){
        policyParam.stringValue = item.value;
      }else if(paramTypeValue.value == '1'){
        policyParam.intValue = item.value;
      }
      policyParam.level = item.level;
      policyParam.alertModelId = item.id;
      policyParam.name = item.name;
      policyParam.statusValue = item.statusValue;
      policyParam.statusType = item.statusType;
      policyParam.methodIds = item.methodIds?.join(',');
      policyParam.operator = item.operator;
      policyParam.sortId = item.sort;
      addPolicyRows.value.push(policyParam);
    }
  })
}

function setParamsType(val){
  paramsList.value.forEach(item=>{
    if(item.paramCode == val){
      form.value.paramType = item.paramType;
    }
  })
}

//判断限值后一项值要比前一项小
function handleValueChange(row){
  let flag = true;
  const selectedRowsNow = proxy.$refs.policyTable.getSelectionRows();
  if(selectedRowsNow.length>0){
    selectedRowsNow.forEach(item=>{
      if(item.sort < row.sort){
        if(item.value > row.value){
          flag = false;
        }
      }else if(item.sort > row.sort){
        if(item.value < row.value){
          flag = false;
        }
      }
    })
  }
  if(!flag){
    colorValue.value[row.sort] = true;
    ElMessageBox.alert('已勾选的告警策略限值填写不合理', '提示', {
      confirmButtonText: '确定',
      center: true,
    })
  }else{
    colorValue.value[row.sort] = false;
  }
  return flag;
}

function judgeIfRightValue(){
  let flag = true;
  const selectedRowsNow = proxy.$refs.policyTable.getSelectionRows();
  if(selectedRowsNow.length>0){
    selectedRowsNow.forEach(item=>{
      if(!handleValueChangeSub(item)){
        flag = false;
      };
      if(item.value === '' || item.methodIds.length === 0){
        flag = false;
      }
    })
  }
  return flag;
}

//判断限值后一项值要比前一项小
function handleValueChangeSub(row){
  let flag = true;
  const selectedRowsNow = proxy.$refs.policyTable.getSelectionRows();
  if(selectedRowsNow.length>0){
    selectedRowsNow.forEach(item=>{
      if(item.sort < row.sort){
        if(item.value > row.value){
          flag = false;
        }
      }else if(item.sort > row.sort){
        if(item.value < row.value){
          flag = false;
        }
      }
    })
  }
  return flag;
}


const validateCell = (data) => {
  if(data === undefined || data === null){
    return false;
  }
  if(typeof data === 'object' && data.value !== undefined){
    // 自定义校验逻辑，根据需求进行修改
    if (typeof data.value === 'number') {
      return data.value !== undefined && data !== null;
    } else if (typeof data.value === 'string') {
      return data.value !== '';
    } else if (typeof data.value === 'boolean') {
      return data.value !== undefined && data.value !== null;
    } else if (Array.isArray(data.value)) {
      return data.value !== [];
    } else if (typeof data.value === 'object') {
      return data.value !== {};
    } else {
      return data.value !== undefined && data.value !== null;
    }
  }else{
    // 自定义校验逻辑，根据需求进行修改
    if (typeof data === 'number') {
      return data !== undefined && data !== null;
    } else if (typeof data === 'string') {
      return data !== '';
    } else if (typeof data === 'boolean') {
      return data !== undefined && data !== null;
    } else if (typeof data === 'object') {
      return data.length !== 0;
    } else if (Array.isArray(data)) {
      return data.length !== 0;
    } else {
      return data !== undefined && data !== null;
    }
  }
 
};
const isInvalid = (value,row) => {
  const rowHadSelected = proxy.$refs.policyTable.getSelectionRows();
  let flag = false;
  rowHadSelected.forEach(item=>{
    if(item.id===row.id){
      flag = true;
    }
  })
  if(!flag){
    return false;
  }
  return !validateCell(value);
};

function changeEnabled(row){
  let param = {
    id:row.id,
    enabled:row.enabled
  }
  updateAlert(param);
}


getList();

</script>
