<template>
  <div class='p-2'>
    <transition :enter-active-class='proxy?.animate.searchAnimate.enter'
                :leave-active-class='proxy?.animate.searchAnimate.leave'>
      <div v-show='showSearch' class='mb-[10px]'>
        <el-card shadow='hover'>
          <el-form ref='queryFormRef' :model='queryParams' :inline='true'>
            <el-form-item label='规则名称' prop='alarmRuleName'>
              <el-input v-model='queryParams.alarmRuleName' placeholder='请输入规则名称' clearable
                        @keyup.enter='handleQuery' />
            </el-form-item>
            <!--            <el-form-item label='报警级别' prop='alarmLevelId'>-->
            <!--              <el-input v-model='queryParams.alarmLevelId' placeholder='请输入报警级别'-->
            <!--                        clearable @keyup.enter='handleQuery' />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label='报警类型' prop='alarmTypeId'>-->
            <!--              <el-input v-model='queryParams.alarmTypeId' placeholder='请输入报警类型'-->
            <!--                        clearable @keyup.enter='handleQuery' />-->
            <!--            </el-form-item>-->
            <el-form-item label='规则类型' prop='ruleType'>
              <el-select v-model='queryParams.ruleType' placeholder='请选择规则类型' clearable>
                <el-option v-for='dict in dms_rule_type' :key='dict.value' :label='dict.label' :value='dict.value' />
              </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 active_flag' :key='dict.value' :label='dict.label' :value='dict.value' />-->
            <!--              </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 active_flag' :key='dict.value' :label='dict.label' :value='dict.value' />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label='报警推送标识' prop='alarmPushFlag'>-->
            <!--              <el-select v-model='queryParams.alarmPushFlag' placeholder='请选择报警推送标识' clearable>-->
            <!--                <el-option v-for='dict in active_flag' :key='dict.value' :label='dict.label' :value='dict.value' />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item>
              <el-button type='primary' icon='Search' @click='handleQuery'>搜索</el-button>
              <el-button icon='Refresh' @click='resetQuery'>重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow='never'>
      <template #header>
        <el-row :gutter='10' class='mb8'>
          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleAdd' v-hasPermi="['dms:alarmRule:add']">新增
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='success' plain icon='Edit' :disabled='single' @click='handleUpdate()'
                       v-hasPermi="['dms:alarmRule:edit']">修改
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='danger' plain icon='Delete' :disabled='multiple' @click='handleDelete()'
                       v-hasPermi="['dms:alarmRule:remove']">删除
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='warning' plain icon='Download' @click='handleExport' v-hasPermi="['dms:alarmRule:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch='showSearch' :columns='columns' :search='true'
                         @queryTable='getList'></right-toolbar>
        </el-row>
      </template>

      <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' v-if='columns[0].visible' />
        <el-table-column label='规则名称' align='center' prop='alarmRuleName' v-if='columns[1].visible' width='130' />
        <el-table-column label='报警级别' align='center' prop='alarmLevelName'
                         v-if='columns[3].visible' />
        <el-table-column label='报警类型' align='center' prop='alarmTypeName'
                         v-if='columns[4].visible' />
        <el-table-column label='规则类型' align='center' prop='ruleType' v-if='columns[5].visible'>
          <template #default='scope'>
            <dict-tag :options='dms_rule_type' :value='scope.row.ruleType' />
          </template>
        </el-table-column>
        <el-table-column label='设备名称' align='center' prop='ruleDeviceName'
                         v-if='columns[6].visible' />
        <el-table-column label='设备模型' align='center' prop='ruleDeviceModeName'
                         v-if='columns[7].visible' width='110' />
        <el-table-column label='属性规则数量' align='center' prop='ruleFunctionTotal' v-if='columns[8].visible' width='110' />
        <el-table-column label='表达式' align='center' prop='triggerExpression' v-if='columns[9].visible' width='120' />
        <el-table-column label='联动标识' align='center' prop='linkFlag' v-if='columns[10].visible'>
          <template #default='scope'>
            <dict-tag :options='active_flag' :value='scope.row.linkFlag' />
          </template>
        </el-table-column>
        <el-table-column label='报警启用状态' align='center' prop='alarmRuleStatus' v-if='columns[11].visible' width='110'>
          <template #default='scope'>
            <dict-tag :options='active_flag' :value='scope.row.alarmRuleStatus' />
          </template>
        </el-table-column>
        <el-table-column label='报警推送标识' align='center' prop='alarmPushFlag' v-if='columns[12].visible' width='110'>
          <template #default='scope'>
            <dict-tag :options='active_flag' :value='scope.row.alarmPushFlag' />
          </template>
        </el-table-column>
        <el-table-column label='报警推送内容' align='center' prop='alarmPushContent' v-if='columns[13].visible' width='110' />
        <el-table-column label='恢复正常推送内容' align='center' prop='alarmRecoverContent' v-if='columns[14].visible'
                         width='130' />
        <el-table-column label='时间范围' align='center' prop='triggerTimeFrame' v-if='columns[15].visible' />
        <el-table-column label='触发阈值次数' align='center' prop='triggerNumber' v-if='columns[16].visible' />
        <el-table-column label='触发死区' align='center' prop='triggerDeadzone' v-if='columns[17].visible' />
        <el-table-column label='描述' align='center' prop='remark' v-if='columns[18].visible' />
        <el-table-column label='操作' align='center' class-name='small-padding fixed-width'>
          <template #default='scope'>
            <el-tooltip content='修改' placement='top'>
              <el-button link type='primary' icon='Edit' @click='handleUpdate(scope.row)'
                         v-hasPermi="['dms:alarmRule:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content='删除' placement='top'>
              <el-button link type='primary' icon='Delete' @click='handleDelete(scope.row)'
                         v-hasPermi="['dms:alarmRule:remove']"></el-button>
            </el-tooltip>
          </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-card>
    <!-- 添加或修改报警规则对话框 -->
    <el-dialog :title='dialog.title' v-model='dialog.visible' width='500px' append-to-body>
      <el-form ref='alarmRuleFormRef' :model='form' :rules='rules' label-width='130px'>
        <el-form-item label='规则名称' prop='alarmRuleName'>
          <el-input v-model='form.alarmRuleName' placeholder='请输入规则名称' />
        </el-form-item>
        <el-form-item label='报警级别' prop='alarmLevelId'>
          <el-select v-model='form.alarmLevelId' placeholder='请选择报警级别'>
            <el-option
              v-for='item in alarmLevelList'
              :key='item.alarmLevelId'
              :label='item.alarmLevelName'
              :value='item.alarmLevelId'
            />
          </el-select>
        </el-form-item>
        <el-form-item label='报警类型' prop='alarmTypeId'>
          <el-select v-model='form.alarmTypeId' placeholder='请选择报警类型'>
            <el-option
              v-for='item in alarmTypeList'
              :key='item.alarmTypeId'
              :label='item.alarmTypeName'
              :value='item.alarmTypeId'
            />
          </el-select>
        </el-form-item>
        <el-form-item label='规则类型' prop='ruleType'>
          <el-radio-group v-model='form.ruleType'>
            <el-radio
              v-for='dict in dms_rule_type'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='设备模型' prop='ruleDeviceModeId'>
          <el-select v-model='form.ruleDeviceModeId' placeholder='请选择设备模型'>
            <el-option
              v-for='item in deviceModeList'
              :key='item.deviceModeId'
              :label='item.deviceModeName'
              :value='item.deviceModeId'
            />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label='设备模型功能' prop='ruleDeviceModeId'>-->
        <!--          <el-input v-model='form.ruleDeviceModeId' placeholder='请输入设备模型功能' />-->
        <!--        </el-form-item>-->
        <el-form-item label='属性规则数量' prop='ruleFunctionTotal'>
          <el-input-number v-model='form.ruleFunctionTotal' placeholder='请输入属性规则数量' style='width: 220px;' />
        </el-form-item>
        <el-form-item label='表达式' prop='triggerExpression'>
          <el-input v-model='form.triggerExpression' placeholder='请输入表达式' />
        </el-form-item>
        <el-form-item label='联动标识' prop='linkFlag'>
          <el-radio-group v-model='form.linkFlag'>
            <el-radio
              v-for='dict in active_flag'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='报警启用状态' prop='alarmRuleStatus'>
          <el-radio-group v-model='form.alarmRuleStatus'>
            <el-radio
              v-for='dict in active_flag'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='报警推送标识' prop='alarmPushFlag'>
          <el-radio-group v-model='form.alarmPushFlag'>
            <el-radio
              v-for='dict in active_flag'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='报警推送内容'>
          <el-input v-model='form.alarmPushContent' type='textarea' placeholder='请输入报警推送内容' />
        </el-form-item>
        <el-form-item label='恢复正常推送内容'>
          <el-input v-model='form.alarmRecoverContent' type='textarea' placeholder='请输入恢复正常推送内容' />
        </el-form-item>
        <el-form-item label='时间范围' prop='triggerTimeFrame'>
          <el-input v-model='form.triggerTimeFrame' placeholder='请输入时间范围' />
        </el-form-item>
        <el-form-item label='触发阈值次数' prop='triggerNumber'>
          <el-input-number v-model='form.triggerNumber' placeholder='请输入触发阈值次数' style='width: 220px;' />
        </el-form-item>
        <el-form-item label='触发死区' prop='triggerDeadzone'>
          <el-input-number v-model='form.triggerDeadzone' placeholder='请输入触发死区' style='width: 220px;' />
        </el-form-item>
        <el-form-item label='描述' prop='remark'>
          <el-input v-model='form.remark' placeholder='请输入描述' />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name='AlarmRule' lang='ts'>
import { listAlarmRule, getAlarmRule, delAlarmRule, addAlarmRule, updateAlarmRule } from '@/api/dms/alarmRule';
import { AlarmRuleVO, AlarmRuleQuery, AlarmRuleForm } from '@/api/dms/alarmRule/types';
import { getBaseAlarmLevelList } from '@/api/dms/alarmLevel';
import { getBaseAlarmTypeList } from '@/api/dms/alarmType';
import { getDmsDeviceModeList } from '@/api/dms/deviceMode';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { active_flag, dms_rule_type } = toRefs<any>(proxy?.useDict('active_flag', 'dms_rule_type'));

const alarmRuleList = ref<AlarmRuleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const alarmRuleFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/** 获取报警级别下拉框 */
const alarmLevelList = ref([]);
const getBaseAlarmLevelListSelect = async () => {
  let res = await getBaseAlarmLevelList(null);
  alarmLevelList.value = res.data;
};

/** 获取报警类型下拉框 */
const alarmTypeList = ref([]);
const getBaseAlarmTypeListSelect = async () => {
  let res = await getBaseAlarmTypeList(null);
  alarmTypeList.value = res.data;
};

/** 获取设备模型下拉框 */
const deviceModeList = ref([]);
const getDmsDeviceModeListSelect = async () => {
  let res = await getDmsDeviceModeList(null);
  deviceModeList.value = res.data;
};

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `报警规则ID`, visible: false },
  { key: 1, label: `规则名称`, visible: true },
  { key: 2, label: `租户编号`, visible: false },
  { key: 3, label: `报警级别`, visible: true },
  { key: 4, label: `报警类型`, visible: true },
  { key: 5, label: `规则类型`, visible: true },
  { key: 6, label: `设备名称`, visible: false },
  { key: 7, label: `设备模型`, visible: true },
  { key: 8, label: `属性规则数量`, visible: true },
  { key: 9, label: `表达式`, visible: true },
  { key: 10, label: `联动标识`, visible: true },
  { key: 11, label: `报警启用状态`, visible: true },
  { key: 12, label: `报警推送标识`, visible: true },
  { key: 13, label: `报警推送内容`, visible: true },
  { key: 14, label: `恢复正常推送内容`, visible: true },
  { key: 15, label: `时间范围`, visible: false },
  { key: 16, label: `触发阈值次数`, visible: false },
  { key: 17, label: `触发死区`, visible: false },
  { key: 18, label: `描述`, visible: true },
  { key: 19, label: `创建部门`, visible: false },
  { key: 20, label: `创建人`, visible: false },
  { key: 21, label: `创建时间`, visible: false },
  { key: 22, label: `更新人`, visible: false },
  { key: 23, label: `更新时间`, visible: false }
]);

const initFormData: AlarmRuleForm = {
  alarmRuleId: undefined,
  alarmRuleName: undefined,
  alarmLevelId: undefined,
  alarmTypeId: undefined,
  ruleType: undefined,
  ruleDeviceId: undefined,
  ruleDeviceModeId: undefined,
  ruleFunctionTotal: undefined,
  triggerExpression: undefined,
  linkFlag: '1',
  alarmRuleStatus: '1',
  alarmPushFlag: '1',
  alarmPushContent: undefined,
  alarmRecoverContent: undefined,
  triggerTimeFrame: undefined,
  triggerNumber: undefined,
  triggerDeadzone: undefined,
  remark: undefined
};
const data = reactive<PageData<AlarmRuleForm, AlarmRuleQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    alarmRuleId: undefined,
    alarmRuleName: undefined,
    alarmLevelId: undefined,
    alarmTypeId: undefined,
    ruleType: undefined,
    ruleDeviceId: undefined,
    ruleDeviceModeId: undefined,
    ruleFunctionTotal: undefined,
    triggerExpression: undefined,
    linkFlag: undefined,
    alarmRuleStatus: undefined,
    alarmPushFlag: undefined,
    alarmPushContent: undefined,
    alarmRecoverContent: undefined,
    triggerTimeFrame: undefined,
    triggerNumber: undefined,
    triggerDeadzone: undefined,
    params: {}
  },
  rules: {
    alarmRuleName: [
      { required: true, message: '规则名称不能为空', trigger: 'blur' }
    ],
    alarmLevelId: [
      { required: true, message: '报警级别不能为空', trigger: 'blur' }
    ],
    triggerExpression: [
      { required: true, message: '表达式不能为空', trigger: 'blur' }
    ],
    alarmTypeId: [
      { required: true, message: '报警类型不能为空', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// /** 获取设备模型功能下拉框 */
// const deviceModeFunctionList = ref([]);
// watch(() => form.value.deviceModeId, (val, oldVal) => {
//   const getDmsDeviceModeFunctionListSelect = async () => {
//     if (val !== null){
//       let res = await getDmsDeviceModeFunctionList({ deviceModeId: val, functionMode: '3'});
//       deviceModeFunctionList.value = res.data;
//     }
//   };
// });

/** 查询报警规则列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAlarmRule(queryParams.value);
  alarmRuleList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  alarmRuleFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AlarmRuleVO[]) => {
  ids.value = selection.map(item => item.alarmRuleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加报警规则';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AlarmRuleVO) => {
  reset();
  const _alarmRuleId = row?.alarmRuleId || ids.value[0];
  const res = await getAlarmRule(_alarmRuleId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改报警规则';
};

/** 提交按钮 */
const submitForm = () => {
  alarmRuleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.alarmRuleId) {
        await updateAlarmRule(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addAlarmRule(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AlarmRuleVO) => {
  const _alarmRuleIds = row?.alarmRuleId || ids.value;
  await proxy?.$modal.confirm('是否确认删除报警规则编号为"' + _alarmRuleIds + '"的数据项？').finally(() => loading.value = false);
  await delAlarmRule(_alarmRuleIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('dms/alarmRule/export', {
    ...queryParams.value
  }, `alarmRule_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getBaseAlarmLevelListSelect();
  getBaseAlarmTypeListSelect();
  getDmsDeviceModeListSelect();
  getList();
});
</script>
