<template>
  <AdminLayout title="默认接收人配置" subtitle="配置任务元数据的默认邮件接收人">
    <div class="meta-email-default">
      <!-- 搜索筛选区域 -->
      <div class="search-bar">
        <div class="search-item">
          <span class="search-label">任务分类</span>
          <el-select 
            v-model="searchForm.category" 
            placeholder="请选择任务分类" 
            clearable
            style="width: 200px"
            @change="handleCategoryChange"
          >
            <el-option
              v-for="category in categoryList"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="search-label">任务元数据</span>
          <el-select 
            v-model="searchForm.metaId" 
            placeholder="请选择任务元数据" 
            clearable
            filterable
            style="width: 300px"
            @change="loadDefaultRecipients"
            :disabled="!searchForm.category"
          >
            <el-option
              v-for="meta in filteredMetaList"
              :key="meta.metaId"
              :label="meta.name"
              :value="meta.metaId"
            />
          </el-select>
        </div>
        <div class="search-actions">
          <el-button type="primary" @click="handleAdd" :disabled="!searchForm.metaId">
            <el-icon><Plus /></el-icon>
            添加接收人
          </el-button>
        </div>
      </div>

      <!-- 提示信息 -->
      <el-alert
        v-if="!searchForm.metaId"
        title="请先选择一个任务元数据"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />

      <!-- 接收人列表 -->
      <el-table 
        v-if="searchForm.metaId"
        :data="recipientList" 
        style="width: 100%" 
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="userEmail" label="邮箱地址" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加接收人 - GenericSelector -->
      <GenericSelector
        v-model:visible="dialogVisible"
        title="选择默认接收人"
        left-title="可选人员"
        right-title="已选人员"
        :fetch-available-api="fetchAllUsers"
        :initialTargetItems="selectedRecipients"
        :filter-selected="filterUsers"
        :item-config="{ id: 'userId', label: 'username', sublabel: 'userEmail' }"
        :use-tree="true"
        :tree-transform="transformUserToTree"
        :tree-props="{ children: 'children', label: 'username', id: 'userId' }"
        :only-leaf-selectable="true"
        unit-name="人"
        search-placeholder="搜索用户姓名或邮箱..."
        @confirm="handleUserConfirm"
        @cancel="resetUserSelector"
      />
    </div>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { AdminLayout } from '@/views/admin';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { crontabApi } from '@/apis/crontab';
import { userApi } from '@/apis/system';
import {GenericSelector} from '@/components';
import type { TaskMeta, EmailDefault, UserVO, ResultDomain } from '@/types';

defineOptions({
  name: 'MetaEmailDefaultView'
});

const loading = ref(false);
const submitting = ref(false);
const dialogVisible = ref(false);

// 搜索表单
const searchForm = reactive({
  category: '',
  metaId: ''
});

// Meta列表
const metaList = ref<TaskMeta[]>([]);

// 分类列表 - 从metaList中提取唯一的category
const categoryList = computed(() => {
  const categories = metaList.value
    .map(meta => meta.category)
    .filter((category): category is string => !!category);
  return Array.from(new Set(categories));
});

// 根据选择的分类过滤Meta列表
const filteredMetaList = computed(() => {
  if (!searchForm.category) {
    return [];
  }
  return metaList.value.filter(meta => meta.category === searchForm.category);
});

// 接收人列表
const recipientList = ref<EmailDefault[]>([]);

// 缓存完整用户列表（包含部门信息），供 selectedRecipients 反查使用
const allUsers = ref<any[]>([]);

// 转换为 GenericSelector 需要的格式（含部门信息）
const selectedRecipients = computed(() => {
  // 用 userId 建索引，方便按默认接收人反查完整用户信息
  const userMap = new Map<string, any>(
    allUsers.value.map(user => [user.userId, user])
  );

  const result = recipientList.value.map(item => {
    const userId = item.userId || '';
    const user = userMap.get(userId);

    if (user) {
      // 有完整用户信息时，直接复用（带 deptID / deptName / parentID）
      return {
        ...user,
        isDept: false
      };
    }

    // 找不到对应用户时，至少保证选择器可用
    return {
      userId,
      username: item.username || '',
      userEmail: item.userEmail || '',
      isDept: false
    };
  });

  console.log('🔵 selectedRecipients computed:', result);
  return result;
});

onMounted(() => {
  loadMetaList();
});

/**
 * 加载Meta列表
 */
async function loadMetaList() {
  try {
    const result = await crontabApi.getAllTaskMeta();
    if (result.success && result.dataList) {
      metaList.value = result.dataList;
    }
  } catch (error) {
    console.error('加载Meta列表失败:', error);
  }
}

/**
 * 分类变化处理
 */
function handleCategoryChange() {
  // 清空 metaId 选择
  searchForm.metaId = '';
  recipientList.value = [];
}

/**
 * 加载默认接收人列表
 */
async function loadDefaultRecipients() {
  if (!searchForm.metaId) {
    recipientList.value = [];
    return;
  }

  try {
    loading.value = true;
    const result = await crontabApi.getEmailDefaultByMetaId(searchForm.metaId);
    if (result.success && result.dataList) {
      console.log('🟢 加载到的默认接收人:', result.dataList);
      recipientList.value = result.dataList;
    } else {
      recipientList.value = [];
    }
  } catch (error) {
    console.error('加载默认接收人失败:', error);
    ElMessage.error('加载默认接收人失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 1. 获取所有人员列表的接口方法
 */
async function fetchAllUsers(): Promise<ResultDomain<any>> {
  try {
    const result = await userApi.getUserList({});
    if (result.success && result.dataList) {
      // 转换为 GenericSelector 需要的格式
      const users = result.dataList.map((user: UserVO) => ({
        userId: user.id || '',
        username: user.username || user.email || 'Unknown',
        userEmail: user.email || '',
        deptID: user.deptID,
        deptName: user.deptName,
        parentID: user.parentID
      }));

      // 缓存完整用户列表，给 selectedRecipients 使用
      allUsers.value = users;

      return {
        ...result,
        dataList: users
      };
    }
    return result;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
    return {
      code: 500,
      success: false,
      login: true,
      auth: true,
      message: '获取用户列表失败',
      dataList: []
    } as ResultDomain<any>;
  }
}

/**
 * 2. 过滤方法：从可选项中移除已选项
 * selected 参数已经包含了右侧所有已选的（包括 initial-target-items）
 */
function filterUsers(available: any[], selected: any[]): any[] {
  const selectedIds = new Set(selected.map((item: any) => item.userId));
  return available.filter(item => !selectedIds.has(item.userId));
}

/**
 * 3. 构建多级部门树的方法
 */
function transformUserToTree(flatData: any[]): any[] {
  if (!flatData || flatData.length === 0) {
    return [];
  }

  const deptMap = new Map();
  const tree: any[] = [];

  flatData.forEach(item => {
    if (!item.deptID) return;

    if (!deptMap.has(item.deptID)) {
      deptMap.set(item.deptID, {
        userId: `dept_${item.deptID}`,
        username: item.deptName || '未分配部门',
        userEmail: '',
        deptID: item.deptID,
        deptName: item.deptName,
        parentID: item.parentID,
        children: [],
        isDept: true
      });
    }

    const deptNode = deptMap.get(item.deptID);
    if (deptNode) {
      deptNode.children.push({
        ...item,
        isDept: false
      });
    }
  });

  const allDepts = Array.from(deptMap.values());
  const deptTreeMap = new Map();

  allDepts.forEach(dept => {
    deptTreeMap.set(dept.deptID, { ...dept });
  });

  allDepts.forEach(dept => {
    const node = deptTreeMap.get(dept.deptID);
    if (!node) return;

    if (!dept.parentID || dept.parentID === '0' || dept.parentID === '') {
      tree.push(node);
    } else {
      const parent = deptTreeMap.get(dept.parentID);
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        const users = node.children || [];
        node.children = [];
        parent.children.push(node);
        node.children = users;
      } else {
        tree.push(node);
      }
    }
  });

  return tree;
}

/**
 * 4. 显示用户选择器
 */
function handleAdd() {
  if (!searchForm.metaId) {
    ElMessage.warning('请先选择任务元数据');
    return;
  }
  dialogVisible.value = true;
}

/**
 * 5. 确认选择用户
 */
async function handleUserConfirm(selected: any[]) {
  // 过滤掉部门节点
  const userItems = selected.filter(item => item.isDept !== true);
  
  // 找出新增的用户（不在 recipientList 中的）
  const existingIds = new Set(recipientList.value.map(item => item.userId));
  const newUsers = userItems.filter(user => !existingIds.has(user.userId));
  
  if (newUsers.length === 0) {
    ElMessage.info('没有新增的用户');
    dialogVisible.value = false;
    return;
  }

  // 验证邮箱
  const userWithoutEmail = newUsers.find(user => !user.userEmail);
  if (userWithoutEmail) {
    ElMessage.warning(`用户 ${userWithoutEmail.username} 没有邮箱地址，无法添加`);
    return;
  }

  try {
    submitting.value = true;

    // 批量添加新用户
    const promises = newUsers.map(user => {
      return crontabApi.createEmailDefault({
        metaId: searchForm.metaId,
        userId: user.userId,
        userEmail: user.userEmail,
        username: user.username
      });
    });

    const results = await Promise.all(promises);
    const successCount = results.filter(r => r.success).length;

    if (successCount > 0) {
      ElMessage.success(`成功添加 ${successCount} 个默认接收人`);
      dialogVisible.value = false;
      loadDefaultRecipients();
    } else {
      ElMessage.error('添加失败');
    }
  } catch (error) {
    console.error('添加默认接收人失败:', error);
    ElMessage.error('添加默认接收人失败');
  } finally {
    submitting.value = false;
  }
}

/**
 * 6. 取消/重置选择器
 */
function resetUserSelector() {
  console.log('✖ 取消选择');
}


/**
 * 删除接收人
 */
async function handleDelete(row: EmailDefault) {
  try {
    await ElMessageBox.confirm(
      `确定删除用户"${row.username}"作为默认接收人吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await crontabApi.deleteEmailDefault(row.defaultId!);
    if (result.success) {
      ElMessage.success('删除成功');
      loadDefaultRecipients();
    } else {
      ElMessage.error(result.message || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

</script>

<style lang="scss" scoped>
.meta-email-default {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  .search-item {
    display: flex;
    align-items: center;
    gap: 8px;

    .search-label {
      font-weight: 500;
      color: #606266;
      white-space: nowrap;
    }
  }

  .search-actions {
    margin-left: auto;
  }
}
</style>
