<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="ruleName">
              <el-input v-model="queryParams.ruleName" placeholder="请输入规则名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="报警类型" prop="alarmType">
              <el-select v-model="queryParams.alarmType" placeholder="请选择报警类型" clearable>
                <el-option v-for="item in alarmTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="enabled">
              <el-select v-model="queryParams.enabled" placeholder="请选择状态" clearable>
                <el-option label="启用" value="1" />
                <el-option label="停用" value="0" />
              </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="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Bell" @click="handleScan">扫描报警</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="ruleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="规则名称" prop="ruleName" min-width="160" />
        <el-table-column label="版本" prop="version" width="100" />
        <el-table-column label="是否启用" align="center" width="90">
          <template #default="scope">{{ scope.row.enabled === '1' ? '启用' : '停用' }}</template>
        </el-table-column>
        <el-table-column label="生效时间起" prop="effectiveStart" min-width="160" />
        <el-table-column label="生效时间止" prop="effectiveEnd" min-width="160" />
        <el-table-column label="报警类型" min-width="130">
          <template #default="scope">{{ formatAlarmType(scope.row.alarmType) }}</template>
        </el-table-column>
        <el-table-column label="报警等级" width="110">
          <template #default="scope">
            <dict-tag :options="alarm_level" :value="scope.row.alarmLevel" />
          </template>
        </el-table-column>
        <el-table-column label="绑定设备" min-width="180" show-overflow-tooltip>
          <template #default="scope">{{ formatBindDevices(scope.row.bindDeviceIds) }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="150">
          <template #default="scope">
            <el-tooltip content="绑定设备" placement="top">
              <el-button link type="primary" icon="Connection" @click="handleBind(scope.row)" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="820px">
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName"><el-input v-model="form.ruleName" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用"><el-switch v-model="form.enabled" active-value="1" inactive-value="0" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警等级">
              <el-select v-model="form.alarmLevel" placeholder="请选择报警等级" clearable>
                <el-option v-for="dict in alarm_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生效时间起"><el-date-picker v-model="form.effectiveStart" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生效时间止"><el-date-picker v-model="form.effectiveEnd" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警类型" prop="alarmType">
              <el-select v-model="form.alarmType" @change="resetRuleEditor">
                <el-option v-for="item in alarmTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.alarmType !== '5'" :span="12">
            <el-form-item label="采集字段">
              <el-select v-model="ruleEditor.field" filterable placeholder="请选择能源指标">
                <el-option v-for="item in metricOptions" :key="item.collectionField" :label="formatMetricLabel(item)" :value="item.collectionField" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col v-if="form.alarmType === '1'" :span="24">
            <el-form-item label="阈值规则">
              <div class="rule-inline">
                <el-input-number v-model="ruleEditor.min" placeholder="下限" controls-position="right" />
                <el-input-number v-model="ruleEditor.max" placeholder="上限" controls-position="right" />
              </div>
            </el-form-item>
          </el-col>

          <el-col v-if="form.alarmType === '2'" :span="24">
            <el-form-item label="多级规则">
              <div class="rule-table-wrap">
                <el-table border :data="multiLevelRows">
                  <el-table-column label="等级" min-width="120">
                    <template #default="scope">
                      <el-select v-model="scope.row.level" placeholder="请选择等级">
                        <el-option v-for="dict in alarm_level" :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" width="140">
                    <template #default="scope">
                      <el-select v-model="scope.row.operator">
                        <el-option label="大于" value="gt" />
                        <el-option label="小于" value="lt" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="数值" width="180">
                    <template #default="scope"><el-input-number v-model="scope.row.value" controls-position="right" /></template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="80">
                    <template #default="scope"><el-button link type="primary" icon="Delete" @click="multiLevelRows.splice(scope.$index, 1)" /></template>
                  </el-table-column>
                </el-table>
                <el-button class="mt-2" type="primary" plain icon="Plus" @click="addMultiLevelRow">新增等级</el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col v-if="form.alarmType === '3'" :span="24">
            <el-form-item label="持续规则">
              <div class="rule-inline">
                <el-select v-model="ruleEditor.direction" class="operator-select">
                  <el-option label="大于上限" value="max" />
                  <el-option label="小于下限" value="min" />
                </el-select>
                <el-input-number v-model="ruleEditor.threshold" placeholder="阈值" controls-position="right" />
                <el-input-number v-model="ruleEditor.time" :min="0" placeholder="持续毫秒" controls-position="right" />
              </div>
            </el-form-item>
          </el-col>

          <el-col v-if="form.alarmType === '4'" :span="24">
            <el-form-item label="变化率规则">
              <div class="rule-inline">
                <el-select v-model="ruleEditor.direction" class="operator-select">
                  <el-option label="上升/波动" value="up" />
                  <el-option label="下降/波动" value="down" />
                </el-select>
                <el-input v-model="ruleEditor.rate" placeholder="如 20 或 20%" class="value-input" />
                <el-input-number v-model="ruleEditor.time" :min="0" placeholder="窗口毫秒" controls-position="right" />
              </div>
            </el-form-item>
          </el-col>

          <el-col v-if="form.alarmType === '5'" :span="24">
            <el-form-item label="停机规则">
              <el-input-number v-model="ruleEditor.time" :min="0" placeholder="超时毫秒" controls-position="right" />
            </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 v-model="bindDialog.visible" title="绑定设备" append-to-body width="880px">
      <el-form :model="bindQueryParams" :inline="true" class="bind-search-form">
        <el-form-item label="关键字">
          <el-input
            v-model="bindQueryParams.keyword"
            placeholder="设备ID/名称/编号"
            clearable
            @keyup.enter="handleBindQuery"
            @clear="handleBindQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleBindQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetBindQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="bindTableRef"
        v-loading="bindDeviceLoading"
        border
        :data="bindDeviceList"
        row-key="deviceId"
        max-height="460"
        @selection-change="handleBindSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="设备ID" prop="deviceId" min-width="130" />
        <el-table-column label="设备名称" prop="deviceName" min-width="150" />
        <el-table-column label="设备编号" prop="deviceCode" min-width="140" />
        <el-table-column label="安装位置" prop="installPositionName" min-width="220" show-overflow-tooltip />
      </el-table>
      <pagination
        v-show="bindDeviceTotal > 0"
        v-model:page="bindQueryParams.pageNum"
        v-model:limit="bindQueryParams.pageSize"
        :total="bindDeviceTotal"
        @pagination="getBindDeviceList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBind">确 定</el-button>
          <el-button @click="bindDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AlarmRule" lang="ts">
import { addAlarmRule, bindAlarmRuleDevices, delAlarmRule, getAlarmRule, listAlarmRule, scanAlarmRule, updateAlarmRule } from '@/api/ems/alarmRule';
import { AlarmRuleForm, AlarmRuleQuery, AlarmRuleVO } from '@/api/ems/alarmRule/types';
import { listEnergyMetric } from '@/api/ems/energyMetric';
import { EnergyMetricVO } from '@/api/ems/energyMetric/types';
import { listMeasuringDevice } from '@/api/ems/measuringDevice';
import { MeasuringDeviceVO } from '@/api/ems/measuringDevice/types';

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

const alarmTypeOptions = [
  { label: '阈值报警', value: '1' },
  { label: '多级阈值报警', value: '2' },
  { label: '持续时间报警', value: '3' },
  { label: '变化率报警', value: '4' },
  { label: '停机报警', value: '5' }
];
const alarmTypeMap = Object.fromEntries(alarmTypeOptions.map((item) => [item.value, item.label]));

const ruleList = ref<AlarmRuleVO[]>([]);
const metricOptions = ref<EnergyMetricVO[]>([]);
const deviceOptions = ref<MeasuringDeviceVO[]>([]);
const bindDeviceList = ref<MeasuringDeviceVO[]>([]);
const bindDeviceTotal = ref(0);
const bindDeviceLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const queryFormRef = ref<ElFormInstance>();
const ruleFormRef = ref<ElFormInstance>();
const bindTableRef = ref();
const dialog = reactive<DialogOption>({ visible: false, title: '' });
const bindDialog = reactive<DialogOption>({ visible: false, title: '' });
const currentBindRule = ref<AlarmRuleVO>();
const bindSelectedDeviceIds = ref<string[]>([]);
const syncingBindSelection = ref(false);
const bindQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
});

const initFormData: AlarmRuleForm = {
  id: undefined,
  ruleName: '',
  enabled: '1',
  effectiveStart: '',
  effectiveEnd: '',
  alarmType: '1',
  alarmRule: {},
  alarmLevel: '',
  bindDeviceIds: []
};

const data = reactive<PageData<AlarmRuleForm, AlarmRuleQuery>>({
  form: { ...initFormData },
  queryParams: { pageNum: 1, pageSize: 10, ruleName: '', alarmType: '', enabled: '' },
  rules: {
    ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
    alarmType: [{ required: true, message: '报警类型不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
const ruleEditor = reactive<any>({});
const multiLevelRows = ref<Array<{ level: string; operator: string; value: number | undefined }>>([]);

const formatAlarmType = (value?: string | number) => alarmTypeMap[String(value || '')] || String(value || '');
const formatMetricLabel = (item: EnergyMetricVO) => `${item.metricName || item.collectionField}${item.unit ? `(${item.unit})` : ''}`;
const formatBindDevices = (deviceIds?: string[]) => {
  const ids = deviceIds || [];
  if (!ids.length) return '全部设备';
  const nameMap = new Map(deviceOptions.value.map((item) => [String(item.deviceId), item.deviceName || item.deviceId || '']));
  return ids.map((id) => nameMap.get(String(id)) || id).join('、');
};

const resetRuleEditor = () => {
  Object.keys(ruleEditor).forEach((key) => delete ruleEditor[key]);
  ruleEditor.field = '';
  ruleEditor.min = undefined;
  ruleEditor.max = undefined;
  ruleEditor.direction = 'max';
  ruleEditor.threshold = undefined;
  ruleEditor.time = undefined;
  ruleEditor.rate = '';
  multiLevelRows.value = [{ level: '1', operator: 'gt', value: undefined }];
};

const loadRuleEditor = (rule: Record<string, any> = {}) => {
  resetRuleEditor();
  ruleEditor.field = rule.field || '';
  if (form.value.alarmType === '1') {
    ruleEditor.min = rule.min;
    ruleEditor.max = rule.max;
  } else if (form.value.alarmType === '2') {
    multiLevelRows.value = Array.isArray(rule.levels)
      ? rule.levels.map((item: any) => ({ level: item.level, operator: item.operator || item.type || 'gt', value: item.value ?? item.max ?? item.min }))
      : Object.entries(rule)
          .filter(([key]) => key !== 'field')
          .map(([level, item]: any) => ({ level, operator: item.operator || item.type || (item.max !== undefined ? 'gt' : 'lt'), value: item.value ?? item.max ?? item.min }));
  } else if (form.value.alarmType === '3') {
    ruleEditor.direction = rule.max !== undefined ? 'max' : 'min';
    ruleEditor.threshold = rule.max ?? rule.min;
    ruleEditor.time = rule.time;
  } else if (form.value.alarmType === '4') {
    ruleEditor.direction = rule.up !== undefined ? 'up' : 'down';
    ruleEditor.rate = rule.up ?? rule.down ?? '';
    ruleEditor.time = rule.time;
  } else if (form.value.alarmType === '5') {
    ruleEditor.time = rule.time;
  }
};

const buildAlarmRule = () => {
  if (form.value.alarmType === '1') return { field: ruleEditor.field, min: ruleEditor.min, max: ruleEditor.max };
  if (form.value.alarmType === '2') return { field: ruleEditor.field, levels: multiLevelRows.value.filter((item) => item.level && item.value !== undefined) };
  if (form.value.alarmType === '3') return { field: ruleEditor.field, [ruleEditor.direction || 'max']: ruleEditor.threshold, time: ruleEditor.time };
  if (form.value.alarmType === '4') return { field: ruleEditor.field, [ruleEditor.direction || 'up']: ruleEditor.rate, time: ruleEditor.time };
  return { time: ruleEditor.time };
};

const addMultiLevelRow = () => {
  const nextLevel = String(Math.min(multiLevelRows.value.length + 1, 5));
  multiLevelRows.value.push({ level: nextLevel, operator: 'gt', value: undefined });
};

const loadOptions = async () => {
  const [metricRes, deviceRes] = await Promise.all([
    listEnergyMetric({ pageNum: 1, pageSize: 1000 }),
    listMeasuringDevice({ pageNum: 1, pageSize: 1000 })
  ]);
  metricOptions.value = (metricRes as any).rows || [];
  deviceOptions.value = (deviceRes as any).rows || [];
};

const syncBindTableSelection = async () => {
  await nextTick();
  syncingBindSelection.value = true;
  bindTableRef.value?.clearSelection?.();
  bindDeviceList.value.forEach((item) => {
    if (bindSelectedDeviceIds.value.includes(String(item.deviceId))) {
      bindTableRef.value?.toggleRowSelection?.(item, true);
    }
  });
  syncingBindSelection.value = false;
};

const getBindDeviceList = async () => {
  bindDeviceLoading.value = true;
  try {
    const res = await listMeasuringDevice(bindQueryParams);
    bindDeviceList.value = (res as any).rows || [];
    bindDeviceTotal.value = (res as any).total || 0;
    const deviceMap = new Map(deviceOptions.value.map((item) => [String(item.deviceId), item]));
    bindDeviceList.value.forEach((item) => {
      if (item.deviceId) deviceMap.set(String(item.deviceId), item);
    });
    deviceOptions.value = Array.from(deviceMap.values());
    await syncBindTableSelection();
  } finally {
    bindDeviceLoading.value = false;
  }
};

const handleBindQuery = () => {
  bindQueryParams.pageNum = 1;
  getBindDeviceList();
};

const resetBindQuery = () => {
  bindQueryParams.pageNum = 1;
  bindQueryParams.keyword = '';
  getBindDeviceList();
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listAlarmRule(queryParams.value);
    ruleList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.value = { ...initFormData, bindDeviceIds: [] };
  resetRuleEditor();
  ruleFormRef.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.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增报警规则';
};
const handleUpdate = async (row?: AlarmRuleVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getAlarmRule(id);
  form.value = { ...res.data, bindDeviceIds: res.data.bindDeviceIds || [] };
  loadRuleEditor(res.data.alarmRule || {});
  dialog.visible = true;
  dialog.title = '修改报警规则';
};
const submitForm = () => {
  ruleFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    const payload = { ...form.value, alarmRule: buildAlarmRule() };
    if (payload.id) await updateAlarmRule(payload);
    else await addAlarmRule(payload);
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    await getList();
  });
};
const handleDelete = async (row?: AlarmRuleVO) => {
  const deleteIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除报警规则编号为"' + deleteIds + '"的数据项？');
  await delAlarmRule(deleteIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const handleScan = async () => {
  const res: any = await scanAlarmRule();
  proxy?.$modal.msgSuccess(`扫描完成，新增 ${res.data?.created || 0} 条报警`);
};
const cancel = () => {
  dialog.visible = false;
  reset();
};

const handleBind = async (row: AlarmRuleVO) => {
  currentBindRule.value = row;
  bindSelectedDeviceIds.value = [...(row.bindDeviceIds || [])].map(String);
  bindDialog.visible = true;
  bindQueryParams.pageNum = 1;
  bindQueryParams.keyword = '';
  await getBindDeviceList();
};
const handleBindSelectionChange = (selection: MeasuringDeviceVO[]) => {
  if (syncingBindSelection.value) return;
  const currentPageIds = bindDeviceList.value.map((item) => String(item.deviceId)).filter(Boolean);
  const selectedIds = selection.map((item) => String(item.deviceId)).filter(Boolean);
  const nextIds = new Set(bindSelectedDeviceIds.value.filter((id) => !currentPageIds.includes(id)));
  selectedIds.forEach((id) => nextIds.add(id));
  bindSelectedDeviceIds.value = Array.from(nextIds);
};
const submitBind = async () => {
  if (!currentBindRule.value?.id) return;
  await bindAlarmRuleDevices({ id: currentBindRule.value.id, deviceIds: bindSelectedDeviceIds.value });
  proxy?.$modal.msgSuccess('绑定成功');
  bindDialog.visible = false;
  await getList();
};

onMounted(async () => {
  resetRuleEditor();
  await loadOptions();
  await getList();
});
</script>

<style scoped>
.rule-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.rule-table-wrap {
  width: 100%;
}

.operator-select {
  width: 140px;
}

.value-input {
  width: 180px;
}

.bind-search-form {
  margin-bottom: 10px;
}
</style>
