<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" label-width="82px">
            <el-form-item label="通知组" prop="groupId">
              <el-select v-model="queryParams.groupId" placeholder="请选择通知组" clearable filterable style="width: 220px">
                <el-option v-for="item in groupOptions" :key="item.id" :label="item.groupName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="启用状态" prop="isEnable">
              <el-select v-model="queryParams.isEnable" placeholder="请选择启用状态" clearable style="width: 160px">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.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="['ems/base:alarmNotifyGroupUser: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:alarmNotifyGroupUser: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:alarmNotifyGroupUser:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ems/base:alarmNotifyGroupUser: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="alarmNotifyGroupUserList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" 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="通知组" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ resolveGroupName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="用户名称" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            {{ resolveUserDisplayName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="手机号" align="center" prop="phone" min-width="140" />
        <el-table-column v-if="columns[4].visible" label="邮箱" align="center" prop="email" min-width="200" show-overflow-tooltip />
        <el-table-column v-if="columns[5].visible" label="启用状态" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="statusOptions" :value="scope.row.isEnable" />
          </template>
        </el-table-column>
        <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:alarmNotifyGroupUser:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:alarmNotifyGroupUser:remove']" />
            </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="620px" append-to-body>
      <el-form ref="alarmNotifyGroupUserFormRef" :model="form" :rules="rules" label-width="88px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="通知组" prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择通知组" filterable style="width: 100%">
                <el-option v-for="item in groupOptions" :key="item.id" :label="item.groupName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通知用户" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择通知用户" filterable style="width: 100%" @change="handleUserChange">
                <el-option v-for="item in userOptions" :key="item.userId" :label="buildUserOptionLabel(item)" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="用户名称">
              <el-input :model-value="resolveUserDisplayName(form)" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="form.phone" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="form.email" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isEnable">
              <el-radio-group v-model="form.isEnable">
                <el-radio v-for="item in statusOptions" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </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="AlarmNotifyGroupUser" lang="ts">
import { useDict } from '@/utils/dict';
import { listAlarmNotifyGroupAll } from '@/api/ems/base/alarmNotifyGroup';
import { listAlarmNotifyGroupUser, getAlarmNotifyGroupUser, delAlarmNotifyGroupUser, addAlarmNotifyGroupUser, updateAlarmNotifyGroupUser } from '@/api/ems/base/alarmNotifyGroupUser';
import type { AlarmNotifyGroupVO } from '@/api/ems/base/alarmNotifyGroup/types';
import type { AlarmNotifyGroupUserVO, AlarmNotifyGroupUserQuery, AlarmNotifyGroupUserForm } from '@/api/ems/base/alarmNotifyGroupUser/types';
import { optionSelect } from '@/api/system/user';
import type { UserVO } from '@/api/system/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dict = reactive({
  type: useDict('sys_normal_disable') as any
});

const statusOptions = computed(() => dict.type.sys_normal_disable ?? []);
const groupOptions = ref<AlarmNotifyGroupVO[]>([]);
const userOptions = ref<UserVO[]>([]);

const alarmNotifyGroupUserList = ref<AlarmNotifyGroupUserVO[]>([]);
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 columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '通知组', visible: true, children: [] },
  { key: 2, label: '用户名称', visible: true, children: [] },
  { key: 3, label: '手机号', visible: true, children: [] },
  { key: 4, label: '邮箱', visible: true, children: [] },
  { key: 5, label: '启用状态', visible: true, children: [] }
]);

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

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

const createFormData = (): AlarmNotifyGroupUserForm => ({
  id: undefined,
  groupId: undefined,
  groupName: undefined,
  userId: undefined,
  userName: undefined,
  nickName: undefined,
  phone: undefined,
  email: undefined,
  isEnable: '0'
});

const data = reactive<PageData<AlarmNotifyGroupUserForm, AlarmNotifyGroupUserQuery>>({
  form: createFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    groupId: undefined,
    userName: undefined,
    phone: undefined,
    email: undefined,
    isEnable: undefined,
    params: {}
  },
  rules: {
    groupId: [{ required: true, message: '通知组不能为空', trigger: 'change' }],
    userId: [{ required: true, message: '通知用户不能为空', trigger: 'change' }]
  }
});

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

const buildUserOptionLabel = (user: UserVO) => `${user.nickName || user.userName}${user.userName ? ` (${user.userName})` : ''}`;

const resolveGroupName = (row?: Partial<AlarmNotifyGroupUserVO> | null) =>
  row?.groupName || groupOptions.value.find((item) => item.id === row?.groupId)?.groupName || (row?.groupId ? String(row.groupId) : '-');

const resolveUserDisplayName = (row?: Partial<AlarmNotifyGroupUserVO> | Partial<AlarmNotifyGroupUserForm> | null) =>
  row?.nickName || row?.userName || userOptions.value.find((item) => item.userId === row?.userId)?.nickName || row?.userId || '-';

const syncUserSnapshot = (userId?: string | number) => {
  const selectedUser = userOptions.value.find((item) => item.userId === userId);
  // 用户名称、手机号、邮箱都属于人员主数据，新增成员时直接从用户档案带入，避免人工录错。
  form.value.userName = selectedUser?.userName;
  form.value.nickName = selectedUser?.nickName;
  form.value.phone = selectedUser?.phonenumber;
  form.value.email = selectedUser?.email;
};

const loadOptions = async () => {
  const [groupRes, userRes] = await Promise.all([listAlarmNotifyGroupAll(), optionSelect()]);
  groupOptions.value = (((groupRes as any).rows ?? (groupRes as any).data ?? groupRes) || []) as AlarmNotifyGroupVO[];
  userOptions.value = (((userRes as any).rows ?? (userRes as any).data ?? userRes) || []) as UserVO[];
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listAlarmNotifyGroupUser(queryParams.value);
    alarmNotifyGroupUserList.value = ((res as any).rows ?? []) as AlarmNotifyGroupUserVO[];
    total.value = Number((res as any).total ?? 0);
  } finally {
    loading.value = false;
  }
};

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

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

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

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

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

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加报警通知组成员';
};

const handleUpdate = async (row?: AlarmNotifyGroupUserVO) => {
  reset();
  const targetId = row?.id ?? ids.value[0];
  if (!targetId) {
    return;
  }
  const res = await getAlarmNotifyGroupUser(targetId);
  form.value = {
    ...createFormData(),
    ...((res as any).data ?? {})
  };
  dialog.visible = true;
  dialog.title = '修改报警通知组成员';
};

const handleUserChange = (userId?: string | number) => {
  syncUserSnapshot(userId);
};

const submitForm = () => {
  alarmNotifyGroupUserFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    buttonLoading.value = true;
    try {
      syncUserSnapshot(form.value.userId);
      if (form.value.id) {
        await updateAlarmNotifyGroupUser(form.value);
      } else {
        await addAlarmNotifyGroupUser(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

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

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

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