<template>
  <!-- 添加或修改公告抽屉 -->
  <el-drawer v-model="visibleProxy" :title="title" size="65%" append-to-body :close-on-click-modal="false" @closed="resetForm">
    <el-card shadow="always" class="box-card" style="padding-top: 10px">
      <el-form ref="noticeFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_notice_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 通知渠道 -->
          <el-col :span="24">
            <el-form-item label="通知渠道" prop="channels">
              <el-checkbox-group v-model="form.channels">
                <el-checkbox value="system">系统内通知</el-checkbox>
                <el-checkbox value="email">邮件通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <!-- 有效期设置 -->
          <el-col :span="12">
            <el-form-item label="有效天数">
              <el-input-number v-model="form.validDays" :min="1" :max="365" placeholder="请输入有效天数" style="width: 100%" />
            </el-form-item>
          </el-col>

          <!-- 接收人类型选择 -->
          <el-col :span="24">
            <el-form-item label="接收人类型" prop="receiverType">
              <el-radio-group v-model="form.receiverType" @change="handleReceiverTypeChange">
                <el-radio value="all">
                  <div class="receiver-type-option">
                    <div class="option-title">全部人员</div>
                    <div class="option-desc">向系统内所有用户发送通知</div>
                  </div>
                </el-radio>
                <el-radio value="specific">
                  <div class="receiver-type-option">
                    <div class="option-title">指定人员</div>
                    <div class="option-desc">选择特定的用户接收通知</div>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 接收人选择 - 仅在选择指定人员时显示 -->
          <el-col v-if="form.receiverType === 'specific'" :span="24">
            <el-form-item label="选择接收人" prop="userIds">
              <div class="user-selector">
                <!-- 搜索和选择 -->
                <el-select
                  v-model="form.userIds"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入用户名或昵称搜索"
                  :remote-method="searchUsers"
                  :loading="userSearchLoading"
                  style="width: 100%"
                  collapse-tags
                  collapse-tags-tooltip
                  :max-collapse-tags="5"
                  popper-class="user-select-dropdown"
                  @focus="handleSelectFocus"
                >
                  <el-option
                    v-for="user in userOptions"
                    :key="user.userId"
                    :label="`${user.nickName || user.userName} (${user.userName}) - ${user.deptName || '无部门'}`"
                    :value="user.userId"
                  >
                  </el-option>
                </el-select>

                <!-- 已选用户数量提示 -->
                <div v-if="form.userIds.length > 0" class="selected-count">
                  已选择 {{ form.userIds.length }} 位用户
                  <el-button type="text" size="small" @click="clearSelectedUsers"> 清空 </el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <!-- 全部人员提示 -->
          <el-col v-if="form.receiverType === 'all'" :span="24">
            <el-form-item label=" ">
              <el-alert title="将向系统内所有有效用户发送通知" type="info" :closable="false" show-icon />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="公告内容">
              <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入公告内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <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-drawer>
</template>

<script setup lang="ts">
import { getNotice, addNotice, updateNotice, getUserOptions } from '@/api/system/notice';
import { NoticeForm, NoticeVO } from '@/api/system/notice/types';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object as PropType<NoticeVO | null>,
    default: null
  }
});

const emit = defineEmits(['update:visible', 'save']);

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

// 可见性的双向绑定
const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 根据编辑类型决定标题
const title = computed(() => (props.editType === 'add' ? '添加公告' : '修改公告'));

// 按钮loading
const buttonLoading = ref(false);
const userSearchLoading = ref(false);

// 表单ref
const noticeFormRef = ref<ElFormInstance>();

// 用户选项
const userOptions = ref<any[]>([]);

// 初始化表单数据
const initFormData: NoticeForm = {
  notificationId: undefined,
  title: '',
  content: '',
  status: '0',
  remark: '',
  createByName: '',
  receiverType: 'specific', // 默认为指定人员
  userIds: [],
  channels: ['system'],
  validDays: 30,
  type: 'announcement'
};

// 表单数据
const form = ref<NoticeForm>({ ...initFormData });

// 表单校验规则
const rules = ref({
  title: [{ required: true, message: '公告标题不能为空', trigger: 'blur' }],
  channels: [{ required: true, message: '请选择至少一个通知渠道', trigger: 'change' }],
  receiverType: [{ required: true, message: '请选择接收人类型', trigger: 'change' }],
  userIds: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.receiverType === 'specific' && (!value || value.length === 0)) {
          callback(new Error('请选择接收人'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

/** 接收人类型变化处理 */
const handleReceiverTypeChange = (value: string) => {
  if (value === 'all') {
    // 选择全部人员时清空指定用户
    form.value.userIds = [];
  }
};

/** 下拉框获取焦点时加载默认数据 */
const handleSelectFocus = () => {
  if (userOptions.value.length === 0) {
    loadDefaultUsers();
  }
};

/** 搜索用户 */
const searchUsers = async (query: string) => {
  if (!query.trim()) {
    // 如果搜索词为空，加载默认用户列表
    await loadDefaultUsers();
    return;
  }

  try {
    userSearchLoading.value = true;
    const res = await getUserOptions({
      pageNum: 1,
      pageSize: 50,
      userName: query,
      nickName: query
    });

    userOptions.value = res.data || [];
  } catch (error) {
    proxy?.$modal.msgError('搜索用户失败');
  } finally {
    userSearchLoading.value = false;
  }
};

/** 加载默认用户列表 */
const loadDefaultUsers = async () => {
  try {
    userSearchLoading.value = true;
    const res = await getUserOptions({
      pageNum: 1,
      pageSize: 100
    });

    userOptions.value = res.data || [];
  } catch (error) {
    proxy?.$modal.msgError('加载用户列表失败');
  } finally {
    userSearchLoading.value = false;
  }
};

/** 清空选中的用户 */
const clearSelectedUsers = () => {
  form.value.userIds = [];
};

/** 取消按钮 */
const cancel = () => {
  visibleProxy.value = false;
};

/** 表单重置 */
const resetForm = () => {
  form.value = { ...initFormData };
  noticeFormRef.value?.resetFields();
  userOptions.value = [];
};

/** 提交按钮 */
const submitForm = () => {
  noticeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 构建提交数据
        const submitData = {
          ...form.value,
          channels: JSON.stringify(form.value.channels),
          // 如果是全部人员，则清空userIds，后端会处理
          userIds: form.value.receiverType === 'all' ? [] : form.value.userIds
        };

        if (form.value.notificationId) {
          await updateNotice(submitData);
        } else {
          await addNotice(submitData);
        }
        proxy?.$modal.msgSuccess('操作成功');
        emit('save');
        visibleProxy.value = false;
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// 监听变化 - 修复编辑时数据回显问题
watch(
  [() => props.visible, () => props.editType, () => props.rowData],
  async ([visible, type, data]) => {
    if (visible) {
      resetForm();

      if (type === 'edit' && data) {
        try {
          // 修改操作 - 获取详细信息
          const res = await getNotice(data.notificationId);
          const noticeData = res.data;

          // 首先加载用户列表
          await loadDefaultUsers();

          // 赋值表单数据
          Object.assign(form.value, {
            notificationId: noticeData.notificationId,
            title: noticeData.title,
            content: noticeData.content,
            status: noticeData.status || '0',
            remark: noticeData.remark || '',
            createByName: noticeData.createByName || '',
            validDays: noticeData.validDays || 30,
            userIds: noticeData.userIds || [],
            channels: noticeData.channels
              ? typeof noticeData.channels === 'string'
                ? JSON.parse(noticeData.channels)
                : noticeData.channels
              : ['system'],
            type: 'announcement',
            // 修改接收人类型判断逻辑：直接使用后端返回的 receiverType
            receiverType: noticeData.receiverType || 'specific'
          });

          // 确保选中的用户在选项列表中 - 修复显示问题
          if (noticeData.receiverUsers && noticeData.receiverUsers.length > 0) {
            // 合并用户列表，确保已选用户显示
            const existingUserIds = userOptions.value.map((u) => u.userId);
            noticeData.receiverUsers.forEach((user) => {
              if (!existingUserIds.includes(user.userId)) {
                userOptions.value.push({
                  userId: user.userId,
                  userName: user.userName,
                  nickName: user.nickName,
                  deptName: user.deptName || '无部门'
                });
              }
            });
          }
        } catch (error) {
          proxy?.$modal.msgError('获取通知详情失败');
        }
      } else {
        // 新增操作时加载默认用户列表
        await loadDefaultUsers();
      }
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.user-selector {
  width: 100%;
}

.receiver-type-option {
  display: flex;
  flex-direction: column;
  margin-left: 8px;
}

.option-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  line-height: 1.2;
}

.option-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
  margin-top: 2px;
}

.selected-count {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 优化下拉选项样式 */
:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-select__tags) {
  max-width: calc(100% - 30px);
}

/* 接收人类型选择样式 */
:deep(.el-radio) {
  margin-right: 30px;
  margin-bottom: 12px;
  height: auto;
  line-height: normal;
}

:deep(.el-radio__label) {
  padding-left: 8px;
}
</style>

<!-- 下拉框样式优化 -->
<style scoped>
.user-selector {
  width: 100%;
}

.receiver-type-option {
  display: flex;
  flex-direction: column;
  margin-left: 8px;
}

.option-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  line-height: 1.2;
}

.option-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
  margin-top: 2px;
}

.selected-count {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 接收人类型选择样式 */
:deep(.el-radio) {
  margin-right: 30px;
  margin-bottom: 12px;
  height: auto;
  line-height: normal;
}

:deep(.el-radio__label) {
  padding-left: 8px;
}

/* 优化下拉选项样式 */
:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-select__tags) {
  max-width: calc(100% - 30px);
}

/* el-select 标签显示优化 */
:deep(.el-select .el-select__tags .el-tag) {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

<!-- 专门处理 popper 内容的样式，使用 scoped 和 deep -->
<style scoped lang="scss">
// 使用 ::v-deep 或 :deep() 穿透 popper-class
::v-deep(.user-select-dropdown) {
  max-width: 500px !important;
  min-width: 350px !important;

  .el-select-dropdown__item {
    height: 32px !important;
    padding: 5px 20px !important;
    line-height: 32px !important;
    white-space: nowrap !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
  }

  .el-select-dropdown__item:hover {
    background-color: #f5f7fa;
  }

  .el-select-dropdown__item.is-selected {
    background-color: #e6f7ff;
    color: #1890ff;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  ::v-deep(.user-select-dropdown) {
    max-width: 90vw !important;
  }

  ::v-deep(.el-select .el-select__tags .el-tag) {
    max-width: 150px;
  }
}
</style>
