<template>
  <div class="learning-task-add">
    <!-- 页面头部 -->
    <div class="page-header">
      <button class="btn-back" @click="handleCancel">
        <span class="arrow-left">←</span> 返回
      </button>
      <h2 class="page-title">{{ taskID ? '编辑学习任务' : '创建学习任务' }}</h2>
    </div>

    <div class="task-form">
      <!-- 基本信息 -->
      <section class="form-section">
        <div class="section-header">
          <h3 class="section-title">基本信息</h3>
        </div>
        
        <div class="form-group">
          <label class="form-label required">任务名称</label>
          <input 
            v-model="taskData.learningTask.name" 
            type="text" 
            class="form-input"
            placeholder="请输入任务名称"
            @blur="validateTaskName"
          />
          <span v-if="errors.name" class="error-msg">{{ errors.name }}</span>
        </div>

        <div class="form-group">
          <label class="form-label">任务描述</label>
          <textarea 
            v-model="taskData.learningTask.description" 
            class="form-textarea"
            rows="4"
            placeholder="请输入任务描述"
          ></textarea>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label class="form-label required">开始时间</label>
            <input 
              v-model="taskData.learningTask.startTime" 
              type="datetime-local" 
              class="form-input"
              @blur="validateTime"
            />
            <span v-if="errors.startTime" class="error-msg">{{ errors.startTime }}</span>
          </div>

          <div class="form-group">
            <label class="form-label required">结束时间</label>
            <input 
              v-model="taskData.learningTask.endTime" 
              type="datetime-local" 
              class="form-input"
              @blur="validateTime"
            />
            <span v-if="errors.endTime" class="error-msg">{{ errors.endTime }}</span>
          </div>
        </div>
      </section>

      <!-- 选择课程 -->
      <section class="form-section">
        <div class="section-header">
          <h3 class="section-title">选择课程</h3>
          <button class="btn-secondary" @click="showCourseSelector = true">添加课程</button>
        </div>

        <div v-if="selectedCourses.length === 0" class="empty-tip">
          暂未添加课程，请点击"添加课程"按钮选择
        </div>

        <div v-else class="selected-list">
          <div 
            v-for="(item, index) in selectedCourses" 
            :key="item.courseID"
            class="selected-item"
          >
            <div class="item-info">
              <span class="item-index">{{ index + 1 }}</span>
              <div class="item-content">
                <h4 class="item-title">{{ item.name }}</h4>
                <p class="item-meta">授课老师: {{ item.teacher }} | 时长: {{ item.duration }}分钟</p>
              </div>
            </div>
            <button class="btn-remove" @click="removeCourse(index)">删除</button>
          </div>
        </div>
      </section>

      <!-- 选择文章资源 -->
      <section class="form-section">
        <div class="section-header">
          <h3 class="section-title">选择文章资源</h3>
          <button class="btn-secondary" @click="showResourceSelector = true">添加资源</button>
        </div>

        <div v-if="selectedResources.length === 0" class="empty-tip">
          暂未添加文章资源，请点击"添加资源"按钮选择
        </div>

        <div v-else class="selected-list">
          <div 
            v-for="(item, index) in selectedResources" 
            :key="item.resourceID"
            class="selected-item"
          >
            <div class="item-info">
              <span class="item-index">{{ index + 1 }}</span>
              <div class="item-content">
                <h4 class="item-title">{{ item.title }}</h4>
                <p class="item-meta">作者: {{ item.author || '未知' }} | 浏览: {{ item.viewCount || 0 }}</p>
              </div>
            </div>
            <button class="btn-remove" @click="removeResource(index)">删除</button>
          </div>
        </div>
      </section>

      <!-- 选择用户 -->
      <section class="form-section">
        <div class="section-header">
          <h3 class="section-title">选择学习用户</h3>
          <button class="btn-secondary" @click="showUserSelector = true">添加用户</button>
        </div>

        <div v-if="selectedUsers.length === 0" class="empty-tip">
          暂未添加学习用户，请点击"添加用户"按钮选择
        </div>

        <div v-else class="selected-list">
          <div 
            v-for="(item, index) in selectedUsers" 
            :key="item.id"
            class="selected-item"
          >
            <div class="item-info">
              <span class="item-index">{{ index + 1 }}</span>
              <div class="item-content">
                <h4 class="item-title">{{ item.username }}</h4>
                <p class="item-meta">邮箱: {{ item.email || '未知' }} | 手机: {{ item.phone || '-' }}</p>
              </div>
            </div>
            <button class="btn-remove" @click="removeUser(index)">删除</button>
          </div>
        </div>
      </section>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <button class="btn-primary" @click="handleSubmit" :disabled="submitting">
          {{ submitting ? '提交中...' : (taskID ? '更新任务' : '创建任务') }}
        </button>
        <button class="btn-default" @click="handleCancel">取消</button>
      </div>
    </div>

    <!-- 课程选择器弹窗 -->
    <div v-if="showCourseSelector" class="modal-overlay" @click.self="showCourseSelector = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">选择课程</h3>
          <button class="modal-close" @click="showCourseSelector = false">✕</button>
        </div>
        
        <div class="modal-body">
          <div class="search-box">
            <input 
              v-model="courseSearchKeyword"
              type="text" 
              class="search-input"
              placeholder="搜索课程名称或老师"
              @input="searchCourses"
            />
          </div>

          <div v-if="courseLoading" class="loading-tip">加载中...</div>
          <div v-else-if="availableCourses.length === 0" class="empty-tip">暂无可选课程</div>
          <div v-else class="selector-list">
            <label 
              v-for="course in availableCourses" 
              :key="course.courseID"
              class="selector-item"
            >
              <input 
                type="checkbox"
                :value="course.courseID"
                :checked="isCourseSelected(course.courseID)"
                @change="toggleCourse(course)"
              />
              <div class="selector-item-content">
                <h4 class="selector-item-title">{{ course.name }}</h4>
                <p class="selector-item-meta">{{ course.teacher }} | {{ course.duration }}分钟</p>
              </div>
            </label>
          </div>
        </div>

        <div class="modal-footer">
          <button class="btn-primary" @click="showCourseSelector = false">确定</button>
        </div>
      </div>
    </div>

    <!-- 资源选择器弹窗 -->
    <div v-if="showResourceSelector" class="modal-overlay" @click.self="showResourceSelector = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">选择文章资源</h3>
          <button class="modal-close" @click="showResourceSelector = false">✕</button>
        </div>
        
        <div class="modal-body">
          <div class="search-box">
            <input 
              v-model="resourceSearchKeyword"
              type="text" 
              class="search-input"
              placeholder="搜索文章标题或作者"
              @input="searchResources"
            />
          </div>

          <div v-if="resourceLoading" class="loading-tip">加载中...</div>
          <div v-else-if="availableResources.length === 0" class="empty-tip">暂无可选资源</div>
          <div v-else class="selector-list">
            <label 
              v-for="resource in availableResources" 
              :key="resource.resourceID"
              class="selector-item"
            >
              <input 
                type="checkbox"
                :value="resource.resourceID"
                :checked="isResourceSelected(resource.resourceID)"
                @change="toggleResource(resource)"
              />
              <div class="selector-item-content">
                <h4 class="selector-item-title">{{ resource.title }}</h4>
                <p class="selector-item-meta">{{ resource.author || '未知' }} | {{ resource.viewCount || 0 }}次浏览</p>
              </div>
            </label>
          </div>
        </div>

        <div class="modal-footer">
          <button class="btn-primary" @click="showResourceSelector = false">确定</button>
        </div>
      </div>
    </div>

    <!-- 用户选择器弹窗 -->
    <div v-if="showUserSelector" class="modal-overlay" @click.self="showUserSelector = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">选择学习用户</h3>
          <button class="modal-close" @click="showUserSelector = false">✕</button>
        </div>
        
        <div class="modal-body">
          <div class="search-box">
            <input 
              v-model="userSearchKeyword"
              type="text" 
              class="search-input"
              placeholder="搜索用户名或手机号"
              @input="searchUsers"
            />
          </div>

          <div v-if="userLoading" class="loading-tip">加载中...</div>
          <div v-else-if="availableUsers.length === 0" class="empty-tip">暂无可选用户</div>
          <div v-else class="selector-list">
            <label 
              v-for="user in availableUsers" 
              :key="user.id"
              class="selector-item"
            >
              <input 
                type="checkbox"
                :value="user.id"
                :checked="isUserSelected(user.id)"
                @change="toggleUser(user)"
              />
              <div class="selector-item-content">
                <h4 class="selector-item-title">{{ user.username }}</h4>
                <p class="selector-item-meta">邮箱: {{ user.email || '未知' }} | {{ user.phone || '-' }}</p>
              </div>
            </label>
          </div>
        </div>

        <div class="modal-footer">
          <button class="btn-primary" @click="showUserSelector = false">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { courseApi } from '@/apis/study';
import { resourceApi } from '@/apis/resource';
import { userApi } from '@/apis/system';
import { learningTaskApi } from '@/apis/study';
import type { TaskVO, Course, TaskItemVO } from '@/types/study';
import type { Resource } from '@/types/resource';
import type { SysUser } from '@/types/user';

defineOptions({
  name: 'LearningTaskAdd'
});

defineExpose({
  // 暴露组件实例方法（如果需要）
});

interface Props {
  taskID?: string;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  success: [];
  cancel: [];
}>();

// 表单数据
const taskData = ref<TaskVO>({
  learningTask: {
    name: '',
    description: '',
    startTime: '',
    endTime: '',
    status: 0
  },
  taskCourses: [],
  taskResources: [],
  taskUsers: []
});

// 表单验证错误
const errors = ref({
  name: '',
  startTime: '',
  endTime: ''
});

// 选中的数据
const selectedCourses = ref<Course[]>([]);
const selectedResources = ref<Resource[]>([]);
const selectedUsers = ref<SysUser[]>([]);

// 可选数据
const availableCourses = ref<Course[]>([]);
const availableResources = ref<Resource[]>([]);
const availableUsers = ref<SysUser[]>([]);

// 弹窗控制
const showCourseSelector = ref(false);
const showResourceSelector = ref(false);
const showUserSelector = ref(false);

// 搜索关键词
const courseSearchKeyword = ref('');
const resourceSearchKeyword = ref('');
const userSearchKeyword = ref('');

// 加载状态
const courseLoading = ref(false);
const resourceLoading = ref(false);
const userLoading = ref(false);
const submitting = ref(false);

onMounted(() => {
  if (props.taskID) {
    loadTask();
  }
  loadCourses();
  loadResources();
  loadUsers();
});

// 加载任务数据
async function loadTask() {
  try {
    const res = await learningTaskApi.getTaskById(props.taskID!);
    if (res.success && res.data) {
      taskData.value = res.data as TaskVO;
      // TODO: 根据 taskCourses、taskResources、taskUsers 恢复选中状态
    }
  } catch (error) {
    console.error('加载任务失败:', error);
    ElMessage.error('加载任务失败');
  }
}

// 加载课程列表
async function loadCourses() {
  courseLoading.value = true;
  try {
    const res = await courseApi.getCourseList({ status: 1 }); // 只加载已上线的课程
    if (res.success && res.dataList) {
      availableCourses.value = res.dataList;
    }
  } catch (error) {
    console.error('加载课程失败:', error);
  } finally {
    courseLoading.value = false;
  }
}

// 搜索课程
function searchCourses() {
  // 简单的前端过滤
  if (!courseSearchKeyword.value) {
    loadCourses();
    return;
  }
  
  const keyword = courseSearchKeyword.value.toLowerCase();
  availableCourses.value = availableCourses.value.filter(course => 
    course.name?.toLowerCase().includes(keyword) ||
    course.teacher?.toLowerCase().includes(keyword)
  );
}

// 加载资源列表
async function loadResources() {
  resourceLoading.value = true;
  try {
    const res = await resourceApi.getResourceList({ status: 1 }); // 只加载已发布的资源
    if (res.success && res.dataList) {
      availableResources.value = res.dataList;
    }
  } catch (error) {
    console.error('加载资源失败:', error);
  } finally {
    resourceLoading.value = false;
  }
}

// 搜索资源
function searchResources() {
  if (!resourceSearchKeyword.value) {
    loadResources();
    return;
  }
  
  const keyword = resourceSearchKeyword.value.toLowerCase();
  availableResources.value = availableResources.value.filter(resource => 
    resource.title?.toLowerCase().includes(keyword) ||
    resource.author?.toLowerCase().includes(keyword)
  );
}

// 加载用户列表
async function loadUsers() {
  userLoading.value = true;
  try {
    const res = await userApi.getUserList({});
    if (res.success && res.dataList) {
      availableUsers.value = res.dataList;
    }
  } catch (error) {
    console.error('加载用户失败:', error);
  } finally {
    userLoading.value = false;
  }
}

// 搜索用户
function searchUsers() {
  if (!userSearchKeyword.value) {
    loadUsers();
    return;
  }
  
  const keyword = userSearchKeyword.value.toLowerCase();
  availableUsers.value = availableUsers.value.filter(user => 
    user.username?.toLowerCase().includes(keyword) ||
    user.phone?.includes(keyword) ||
    user.email?.toLowerCase().includes(keyword)
  );
}

// 课程选择相关
function isCourseSelected(courseID?: string) {
  return selectedCourses.value.some(c => c.courseID === courseID);
}

function toggleCourse(course: Course) {
  const index = selectedCourses.value.findIndex(c => c.courseID === course.courseID);
  if (index > -1) {
    selectedCourses.value.splice(index, 1);
  } else {
    selectedCourses.value.push(course);
  }
}

function removeCourse(index: number) {
  selectedCourses.value.splice(index, 1);
}

// 资源选择相关
function isResourceSelected(resourceID?: string) {
  return selectedResources.value.some(r => r.resourceID === resourceID);
}

function toggleResource(resource: Resource) {
  const index = selectedResources.value.findIndex(r => r.resourceID === resource.resourceID);
  if (index > -1) {
    selectedResources.value.splice(index, 1);
  } else {
    selectedResources.value.push(resource);
  }
}

function removeResource(index: number) {
  selectedResources.value.splice(index, 1);
}

// 用户选择相关
function isUserSelected(userID?: string) {
  return selectedUsers.value.some(u => u.id === userID);
}

function toggleUser(user: SysUser) {
  const index = selectedUsers.value.findIndex(u => u.id === user.id);
  if (index > -1) {
    selectedUsers.value.splice(index, 1);
  } else {
    selectedUsers.value.push(user);
  }
}

function removeUser(index: number) {
  selectedUsers.value.splice(index, 1);
}

// 表单验证
function validateTaskName() {
  if (!taskData.value.learningTask.name) {
    errors.value.name = '请输入任务名称';
    return false;
  }
  errors.value.name = '';
  return true;
}

function validateTime() {
  if (!taskData.value.learningTask.startTime) {
    errors.value.startTime = '请选择开始时间';
    return false;
  }
  if (!taskData.value.learningTask.endTime) {
    errors.value.endTime = '请选择结束时间';
    return false;
  }
  if (new Date(taskData.value.learningTask.startTime) >= new Date(taskData.value.learningTask.endTime)) {
    errors.value.endTime = '结束时间必须大于开始时间';
    return false;
  }
  errors.value.startTime = '';
  errors.value.endTime = '';
  return true;
}

function validateForm() {
  const isNameValid = validateTaskName();
  const isTimeValid = validateTime();
  
  if (!isNameValid || !isTimeValid) {
    return false;
  }
  
  if (selectedCourses.value.length === 0 && selectedResources.value.length === 0) {
    ElMessage.warning('请至少选择一个课程或资源');
    return false;
  }
  
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一个学习用户');
    return false;
  }
  
  return true;
}

// 提交表单
async function handleSubmit() {
  if (!validateForm()) {
    return;
  }
  
  submitting.value = true;
  
  try {
    // 组装任务课程数据
    taskData.value.taskCourses = selectedCourses.value.map((course, index) => ({
      courseID: course.courseID,
      courseName: course.name,
      orderNum: index
    } as TaskItemVO));
    
    // 组装任务资源数据
    taskData.value.taskResources = selectedResources.value.map((resource, index) => ({
      resourceID: resource.resourceID,
      resourceName: resource.title,
      orderNum: index
    } as TaskItemVO));
    
    // 组装任务用户数据
    taskData.value.taskUsers = selectedUsers.value.map(user => ({
      userID: user.id,
      userName: user.username,
      status: 0
    } as TaskItemVO));
    
    let res;
    if (props.taskID) {
      res = await learningTaskApi.updateTask(taskData.value);
    } else {
      res = await learningTaskApi.createTask(taskData.value);
    }
    
    if (res.success) {
      ElMessage.success(props.taskID ? '任务更新成功' : '任务创建成功');
      emit('success');
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  } finally {
    submitting.value = false;
  }
}

// 取消
function handleCancel() {
  emit('cancel');
}
</script>

<style lang="scss" scoped>
.learning-task-add {
  padding: 20px;
}

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

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
}

.btn-back {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;

  &:hover {
    color: #409eff;
    border-color: #409eff;
  }

  .arrow-left {
    font-size: 16px;
  }
}

.task-form {
  max-width: 1200px;
}

.form-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;

  &.required::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  transition: border-color 0.3s;
  box-sizing: border-box;

  &:focus {
    outline: none;
    border-color: #409eff;
  }

  &::placeholder {
    color: #c0c4cc;
  }
}

.form-textarea {
  resize: vertical;
  font-family: inherit;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.error-msg {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #f56c6c;
}

.empty-tip {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
  background: #f5f7fa;
  border-radius: 4px;
}

.selected-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.selected-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 6px;
  transition: all 0.3s;

  &:hover {
    background: #ecf5ff;
  }
}

.item-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.item-index {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: #409eff;
  color: #fff;
  border-radius: 50%;
  font-size: 14px;
  font-weight: 600;
}

.item-content {
  flex: 1;
}

.item-title {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 4px 0;
}

.item-meta {
  font-size: 13px;
  color: #909399;
  margin: 0;
}

.btn-remove {
  padding: 6px 16px;
  border: 1px solid #f56c6c;
  background: #fff;
  color: #f56c6c;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.3s;

  &:hover {
    background: #f56c6c;
    color: #fff;
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn-primary,
.btn-secondary,
.btn-default {
  padding: 10px 24px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.btn-primary {
  background: #409eff;
  color: #fff;

  &:hover:not(:disabled) {
    background: #66b1ff;
  }
}

.btn-secondary {
  background: #67c23a;
  color: #fff;
  border: none;

  &:hover {
    background: #85ce61;
  }
}

.btn-default {
  background: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;

  &:hover {
    color: #409eff;
    border-color: #409eff;
  }
}

// 弹窗样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background: #fff;
  border-radius: 8px;
  width: 90%;
  max-width: 700px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.modal-close {
  width: 32px;
  height: 32px;
  border: none;
  background: #f5f7fa;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  color: #909399;
  transition: all 0.3s;

  &:hover {
    background: #ecf5ff;
    color: #409eff;
  }
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px 24px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
}

.search-box {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;

  &:focus {
    outline: none;
    border-color: #409eff;
  }
}

.loading-tip {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 14px;
}

.selector-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selector-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #ecf5ff;
    border-color: #409eff;
  }

  input[type="checkbox"] {
    width: 18px;
    height: 18px;
    cursor: pointer;
  }
}

.selector-item-content {
  flex: 1;
}

.selector-item-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 4px 0;
}

.selector-item-meta {
  font-size: 12px;
  color: #909399;
  margin: 0;
}
</style>

