<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="4" :xs="24">
        <device-tree @deviceInfo="deviceInfo" @node-click="handleQuery" />
      </el-col>
      <el-col :lg="20" :xs="24" >
        <Memo style="width: 1em; height: 1em; margin-right: 8px" />
        <el-text class="mx-1" size="large">配置列表</el-text>
        <el-card shadow="never">
          <el-table
              v-loading="loading"
              ref="ruleListRef"
              :data="pageData"
              style="height: 280px"
              @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
                label="设备名称"
                width="150"
                align="center"
                prop="deviceName"
            />
            <el-table-column
                label="参数项"
                width="250"
                align="center"
                prop="label"
            />
            <el-table-column
                label="规则内容"
                align="center"
                prop="ruleContent"
            />
            <el-table-column
                label="操作"
                align="center"
                prop="unit"
            >
              <template v-slot="{ row}">
                <el-button type="danger" @click="minusItem2(row)" icon="el-icon-minus" style="margin-left:15px;width:25px;height:25px;" circle />
              </template>
            </el-table-column>
          </el-table>
<!--          <pagination
              v-if="total > 0"
              v-model:total="total"
              v-model:page="queryParams.pageNo"
              v-model:limit="queryParams.pageSize"
              @pagination="handleQuery"
          />-->

          <div style="width:100%; height: 20px;"></div>
          <Edit style="width: 1em; height: 1em; margin-right: 8px" />
          <el-text class="mx-1" size="large">配置规则</el-text>
          <el-button type="primary" @click="addItem" icon="el-icon-plus" style="margin-left:15px;width:25px;height:25px;" circle />
          <el-divider />
          <el-text v-if="formDataList.length !==0" class="mx-1" type="primary">关系式成立,则异常报警</el-text>
          <el-form
              ref="ruleFormRef"
              label-width="90px"
          >
              <el-row :gutter="22" style="margin-top:5px;" v-for="(item, index) in formDataList" :key="index">

                <el-col :span="6">
                  <el-select
                      v-model="item.field"
                      placeholder="请选择字段"
                      @change="(e) => change1(e, item)"
                  >
                    <el-option
                        v-for="option in fieldOptions"
                        :key="option.alias"
                        :label="option.filedLabel"
                        :value="option.alias"
                    />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-select
                      v-model="item.rule"
                      placeholder="请选择规则"
                  >
                    <el-option label="小于" value="小于"/>
                    <el-option label="大于" value="大于"/>
                    <el-option label="等于" value="等于"/>
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-input
                      v-model="item.val"
                      placeholder="请输入数值"
                  />
                </el-col>
                <el-col :span="2" v-if="index !== (formDataList.length-1)">
                  <el-select
                      v-model="item.luoji"
                      placeholder="逻辑"
                  >
                    <el-option selected label="且" value="且"/>
                    <el-option label="或" value="或"/>
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" @click="minusItem(index)" icon="el-icon-minus" style="margin-left:15px;width:25px;height:25px;" circle />
                </el-col>
              </el-row>

            <div class="dialog-footer" style="margin-top:20px" v-if="formDataList.length > 0" align="center">
              <el-button type="primary" @click="handleSubmit">确 定</el-button>
            </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ElTable} from "element-plus";

defineOptions({
  name: "rulePage",
  inheritAttrs: false,
});

import {
  rulePage,aliasList,ruleAdd,ruleRemove
} from "@/api/device/rule";
import {deleteDict} from "@/api/system/dict";
const deviceInfo =(value)=>{
  queryParams.deviceNo = value.deviceNo
  queryParams.deviceType = value.deviceType
  handleQuery()
  queryAliasField(value.deviceType)
}

const ruleListRef = ref(ElTable);
const loading = ref(false); //  加载状态
const queryParams = reactive({
  pageNo: 1,
  pageSize: 99999,
});
const total = ref(0); // 数据总数
const pageData = ref([]);
const formDataList = ref([]);
const options = ref([])
const addItem =()=>{
  if(queryParams.deviceNo){
    formDataList.value.push({luoji: '且'})
  }else{
    ElMessage.warning("请先选择设备");
  }
}
const change1 =(val0,item) =>{
  const selectedOption = fieldOptions.value.find(option => option.alias === val0).filedLabel;
  item.fieldStr = selectedOption
}
const minusItem =(index)=>{
  formDataList.value.splice(index,1)
}
const minusItem2 = (row) =>{
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ruleRemove({id: row.id}).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  });
}
// 用户表单数据
const formData = reactive({
  state: 0,
  sex: 0
});

const queryAliasField = (deviceType)=>{
  aliasList({deviceType: deviceType}).then((data)=>{
    fieldOptions.value = data.data
  })
}
const fieldOptions = ref([])
const clickId = ref(null)
/** 查询 */
function handleQuery() {
  loading.value = true;
  if(queryParams.deviceNo){
    rulePage(queryParams)
        .then(({ data }) => {
          pageData.value = data.records;
          total.value = data.totalCount;
        })
        .finally(() => {
          loading.value = false;
        });
  }
}


/** 行选中 */
function handleSelectionChange(selection) {
  if(selection.length > 1){
    const preVal = selection.shift()
    ruleListRef.value.toggleRowSelection(preVal, false);
  }
  clickId.value = null
  if(selection.length === 0){
    formDataList.value = []
  }else{
    clickId.value = selection[0].id
    formDataList.value = JSON.parse(selection[0].ruleExpression)
  }
}



/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  let constStr = ""
  let field = ""
  let label = ""
  if(formDataList.value){
    formDataList.value.forEach(item=>{
      if(!item.field){
        ElMessage.warning("请选择字段");
        return
      }
      if(!item.rule){
        ElMessage.warning("请选择规则");
        return
      }
      if(!item.val){
        ElMessage.warning("请填写规则");
        return
      }
      if(constStr !== ''){
        constStr += item.luoji
      }
      constStr += item.fieldStr + item.rule + item.val
      if(field === ''){
        field = item.field
      }else{
        field += ',' + item.field
      }
      if(label === ''){
        label = item.fieldStr
      }else{
        label += ',' + item.fieldStr
      }
    })
  }
  const params = {id: clickId.value,field: field,label: label,deviceNo: queryParams.deviceNo,ruleContent: constStr,ruleExpression: JSON.stringify(formDataList.value)}
  ruleAdd(params).then((data)=>{
    ElMessage.success(data.msg);
    formDataList.value = []
    handleQuery()
  })
}, 3000);

onMounted?.(() => {
  handleQuery();
});
</script>
