<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" class="query-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="通知组名称" prop="groupName">
              <el-input v-model="queryParams.groupName" placeholder="请输入通知组名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="通知渠道" prop="notifyChannel">
              <el-select v-model="queryParams.notifyChannel" placeholder="请选择通知渠道" clearable style="width: 180px">
                <el-option v-for="item in notifyChannelOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="isEnable">
              <el-select v-model="queryParams.isEnable" placeholder="请选择启用状态" clearable style="width: 160px">
                <el-option v-for="dict in sys_normal_disable" :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" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ems/base:alarmNotifyGroup:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['ems/base:alarmNotifyGroup:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['ems/base:alarmNotifyGroup:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ems/base:alarmNotifyGroup:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="alarmNotifyGroupList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column v-if="columns[0].visible" label="序号" type="index" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="通知组名称" align="center" prop="groupName" min-width="180" show-overflow-tooltip />
        <el-table-column v-if="columns[2].visible" label="通知渠道" align="center" min-width="140">
          <template #default="scope">
            <dict-tag :options="notifyChannelOptions" :value="scope.row.notifyChannel" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="Webhook地址" align="center" prop="webhookUrl" min-width="220" show-overflow-tooltip />
        <el-table-column v-if="columns[4].visible" label="启用状态" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.isEnable" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="备注" align="center" prop="remark" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="110" 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="['ems/base:alarmNotifyGroup:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:alarmNotifyGroup:remove']" />
            </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" width="620px" append-to-body>
      <el-form ref="alarmNotifyGroupFormRef" :model="form" :rules="rules" label-width="96px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="通知组名称" prop="groupName">
              <el-input v-model="form.groupName" placeholder="请输入通知组名称" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通知渠道" prop="notifyChannel">
              <el-select v-model="form.notifyChannel" placeholder="请选择通知渠道" style="width: 100%">
                <el-option v-for="item in notifyChannelOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="Webhook地址" prop="webhookUrl">
          <el-input v-model="form.webhookUrl" placeholder="请输入Webhook地址" maxlength="500" />
        </el-form-item>
        <el-form-item label="启用状态" prop="isEnable">
          <el-radio-group v-model="form.isEnable">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" maxlength="200" show-word-limit 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="AlarmNotifyGroup" lang="ts">
import { addAlarmNotifyGroup, delAlarmNotifyGroup, getAlarmNotifyGroup, listAlarmNotifyGroup, updateAlarmNotifyGroup } from '@/api/ems/base/alarmNotifyGroup';
import type { AlarmNotifyGroupForm, AlarmNotifyGroupQuery, AlarmNotifyGroupVO } from '@/api/ems/base/alarmNotifyGroup/types';

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

const notifyChannelOptions = [
  { label: '站内消息', value: 'SITE' },
  { label: '短信', value: 'SMS' },
  { label: '邮件', value: 'EMAIL' },
  { label: 'Webhook', value: 'WEBHOOK' }
];

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

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '通知组名称', visible: true, children: [] },
  { key: 2, label: '通知渠道', visible: true, children: [] },
  { key: 3, label: 'Webhook地址', visible: true, children: [] },
  { key: 4, label: '启用状态', visible: true, children: [] },
  { key: 5, label: '备注', visible: true, children: [] }
]);

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

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

const createFormData = (): AlarmNotifyGroupForm => ({
  id: undefined,
  groupName: undefined,
  notifyChannel: undefined,
  webhookUrl: undefined,
  // 默认给启用态，避免新建后还要额外点一次状态。
  isEnable: '0',
  remark: undefined
});

const data = reactive<PageData<AlarmNotifyGroupForm, AlarmNotifyGroupQuery>>({
  form: createFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    groupName: undefined,
    notifyChannel: undefined,
    isEnable: undefined
  },
  rules: {
    groupName: [{ required: true, message: '通知组名称不能为空', trigger: 'blur' }],
    notifyChannel: [{ required: true, message: '通知渠道不能为空', trigger: 'change' }]
  }
});

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

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

const reset = () => {
  form.value = createFormData();
  alarmNotifyGroupFormRef.value?.resetFields();
};

const cancel = () => {
  dialog.visible = false;
  reset();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: AlarmNotifyGroupVO[]) => {
  ids.value = selection.map((item) => item.id as string | number);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

const handleAdd = () => {
  reset();
  dialog.title = '新增通知组';
  dialog.visible = true;
};

const handleUpdate = async (row?: AlarmNotifyGroupVO) => {
  reset();
  const id = row?.id ?? ids.value[0];
  const res = await getAlarmNotifyGroup(id);
  Object.assign(form.value, res.data);
  dialog.title = '修改通知组';
  dialog.visible = true;
};

const submitForm = async () => {
  const valid = await alarmNotifyGroupFormRef.value?.validate().catch(() => false);
  if (!valid) {
    return;
  }
  buttonLoading.value = true;
  try {
    // 这里只传业务字段，避免把界面辅助字段误带回后端。
    const payload: AlarmNotifyGroupForm = {
      id: form.value.id,
      groupName: form.value.groupName,
      notifyChannel: form.value.notifyChannel,
      webhookUrl: form.value.webhookUrl,
      isEnable: form.value.isEnable,
      remark: form.value.remark
    };
    if (payload.id) {
      await updateAlarmNotifyGroup(payload);
    } else {
      await addAlarmNotifyGroup(payload);
    }
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    await getList();
  } finally {
    buttonLoading.value = false;
  }
};

const handleDelete = async (row?: AlarmNotifyGroupVO) => {
  const targetIds = row?.id ?? ids.value;
  await proxy?.$modal.confirm(`是否确认删除通知组编号为“${targetIds}”的数据项？`);
  await delAlarmNotifyGroup(targetIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  proxy?.download(
    'ems/base/alarmNotifyGroup/export',
    {
      ...queryParams.value
    },
    `alarmNotifyGroup_${new Date().getTime()}.xlsx`
  );
};

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

<style scoped lang="scss">
.query-card {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.table-card {
  :deep(.el-card__body) {
    padding-top: 10px;
  }
}
</style>
