<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search" placeholder="项目名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" align="center" width="60">
        <template slot-scope="{row}"><span>{{ row.id }}</span></template>
      </el-table-column>
      <el-table-column label="项目名称" min-width="150px">
        <template slot-scope="{row}"><span>{{ row.title }}</span></template>
      </el-table-column>
      <el-table-column label="项目类型" width="120px" align="center">
        <template slot-scope="{row}"><span>{{ row.project_type_display }}</span></template>
      </el-table-column>
      <el-table-column label="教学中心" width="110px" align="center">
        <template slot-scope="{row}"><span>{{ row.teacher_name }}</span></template>
      </el-table-column>
      <el-table-column label="封面" width="80px" align="center">
        <template slot-scope="{row}"><img :src="resolveUrl(row.image)" width="50" height="50" style="object-fit:cover"></template>
      </el-table-column>
      <el-table-column label="学习人数" width="80px" align="center">
        <template slot-scope="{row}"><span>{{ row.students }}</span></template>
      </el-table-column>
      <el-table-column label="地址" width="150px" align="center">
        <template slot-scope="{row}"><span>{{ row.address }}</span></template>
      </el-table-column>
      <el-table-column label="价格" width="120px" align="center">
        <template slot-scope="{row}"><span>{{ row.price }}</span></template>
      </el-table-column>
      <el-table-column label="显示价格" width="80px" align="center">
        <template slot-scope="{row}">
            <el-tag :type="row.show_price ? 'success' : 'info'">{{ row.show_price ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="80px" align="center">
        <template slot-scope="{row}"><span>{{ row.sort_order }}</span></template>
      </el-table-column>
      <el-table-column label="置顶" width="80px" align="center">
        <template slot-scope="{row}">
            <el-tag :type="row.is_top ? 'danger' : 'info'">{{ row.is_top ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80px" align="center">
        <template slot-scope="{row}">
            <el-tag :type="row.is_active ? 'success' : 'info'">{{ row.is_active ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="success" size="mini" @click="handleStudents(row)">学员管理</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="800px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 700px; margin-left:50px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="title">
              <el-input v-model="temp.title" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教学中心" prop="teacher">
              <el-select v-model="temp.teacher" class="filter-item" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in teachers" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="!temp.teacher && (temp.project_type === 'competition' || temp.project_type === 'grading')">
           <el-col :span="24">
             <el-form-item label="自定义主办方" prop="custom_teacher">
               <el-input v-model="temp.custom_teacher" placeholder="未选择教学中心时，可在此输入主办方/机构名称" />
             </el-form-item>
           </el-col>
        </el-row>

        <el-form-item label="封面图片" prop="image">
           <el-upload
            class="avatar-uploader"
            :action="upUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="upHeaders">
            <img v-if="temp.image" :src="resolveUrl(temp.image)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="学习人数" prop="students">
              <el-input v-model.number="temp.students" placeholder="请输入学习人数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址" prop="address">
              <el-input v-model="temp.address" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
             <el-form-item label="时长" prop="duration">
              <el-input v-model="temp.duration" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="价格" prop="price">
                    <el-input v-model="temp.price" type="number" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="显示价格" prop="show_price">
                    <el-switch v-model="temp.show_price" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="置顶" prop="is_top">
                    <el-switch v-model="temp.is_top" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                </el-form-item>
            </el-col>
        </el-row>
        
        <el-row :gutter="20">
             <el-col :span="8">
                <el-form-item label="排序" prop="sort_order">
                    <el-input-number v-model="temp.sort_order" :min="0" :max="9999" style="width: 100%;"></el-input-number>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="是否启用" prop="is_active">
                    <el-switch v-model="temp.is_active" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item label="项目详情" prop="detail">
          <div id="editor"></div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog title="学员管理" :visible.sync="studentDialogVisible" width="800px">
        <div class="filter-container">
            <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="openAddStudent">添加学员</el-button>
        </div>
        <el-table :data="studentList" border fit highlight-current-row style="width: 100%;">
            <el-table-column label="学员姓名" align="center">
                <template slot-scope="{row}"><span>{{ row.student_name }}</span></template>
            </el-table-column>
            <el-table-column label="电话" align="center">
                <template slot-scope="{row}"><span>{{ row.student_phone }}</span></template>
            </el-table-column>
            <el-table-column label="所属项目" align="center">
                <template slot-scope="{row}"><span>{{ row.project_title }}</span></template>
            </el-table-column>
            <el-table-column label="报名时间" align="center">
                <template slot-scope="{row}"><span>{{ row.enrolled_at }}</span></template>
            </el-table-column>
             <el-table-column label="状态" align="center" width="130">
                <template slot-scope="{row}">
                    <el-select v-model="row.status" size="mini" @change="handleStudentStatusChange(row)">
                        <el-option v-for="item in studentStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="{row}">
                    <el-button size="mini" type="danger" @click="removeStudent(row)">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-dialog>

    <el-dialog title="添加学员" :visible.sync="addStudentDialogVisible" width="500px">
        <el-form label-position="left" label-width="90px">
            <el-form-item label="选择学员">
                <el-select v-model="selectedStudentId" filterable remote :remote-method="searchStudents" placeholder="请输入姓名或电话搜索" style="width: 100%">
                    <el-option v-for="item in allStudents" :key="item.id" :label="item.name + ' (' + item.phone + ')'" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addStudentDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmAddStudent">确认</el-button>
        </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<script>
import { getProjects, createProject, updateProject, deleteProject, getTeachers, getStudentProjects, createStudentProject, updateStudentProject, deleteStudentProject, getStudents } from '@/api/crm'
import Pagination from '@/components/Pagination'
import { upUrl, upHeaders } from "@/api/file"
import E from 'wangeditor'

export default {
  name: 'ProjectTable',
  components: { Pagination },
  data() {
    return {
      editor: null,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined,
        project_type: undefined
      },
      teachers: [],
      projectTypeOptions: [
        { label: '小主持语言培训', value: 'training' },
        { label: '赛事管理', value: 'competition' },
        { label: '考级管理', value: 'grading' }
      ],
      temp: {
        id: undefined,
        title: '',
        project_type: 'training',
        teacher: undefined,
        custom_teacher: '',
        image: '',
        students: 0,
        address: '',
        duration: '4 周',
        price: 299.00,
        show_price: true,
        sort_order: 0,
        is_top: false,
        is_active: true,
        detail: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        title: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        // teacher: [{ required: true, message: '请选择负责老师', trigger: 'change' }], // Optional?
      },
      upUrl: upUrl(),
      upHeaders: upHeaders(),

      // Student Management
      studentDialogVisible: false,
      currentProject: null,
      studentList: [],
      addStudentDialogVisible: false,
      selectedStudentId: undefined,
      allStudents: [],
      studentStatusOptions: [
        { label: '已报名', value: 'enrolled' },
        { label: '在读', value: 'studying' },
        { label: '毕业', value: 'graduated' },
        { label: '结束', value: 'finished' }
      ]
    }
  },
  created() {
    // 根据路由 meta 设置默认的项目类型筛选
    if (this.$route.meta.type) {
      this.listQuery.project_type = this.$route.meta.type
    }
    this.getList()
    this.getTeachers()
  },
  watch: {
    '$route.meta.type'(val) {
        this.listQuery.project_type = val
        this.getList()
    }
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy()
      this.editor = null
    }
  },
  methods: {
    getList() {
      this.listLoading = true
      getProjects(this.listQuery).then(response => {
        this.list = response.data.results
        this.total = response.data.count
        this.listLoading = false
      })
    },
    getTeachers() {
      getTeachers().then(response => {
        // 如果后端没有分页，response.data 就是数组
        this.teachers = Array.isArray(response.data) ? response.data : response.data.results
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        project_type: this.listQuery.project_type || 'training',
        teacher: undefined,
        custom_teacher: '',
        image: 'https://images.unsplash.com/photo-1526379095098-d400fd0bf935',
        students: 0,
        address: '',
        duration: '4 周',
        price: 299.00,
        show_price: true,
        sort_order: 0,
        is_top: false,
        is_active: true,
        detail: ''
      }
    },
    resolveUrl(url) {
      if (!url) return ''
      if (url.startsWith('http://localhost:8000/media/')) {
        return url.replace('http://localhost:8000', '')
      }
      if (url.startsWith('http://127.0.0.1:8000/media/')) {
        return url.replace('http://127.0.0.1:8000', '')
      }
      return url
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.initEditor()
        this.editor.txt.html('')
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createProject(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.initEditor()
        this.editor.txt.html(this.temp.detail)
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateProject(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    initEditor() {
      if (this.editor) return
      this.editor = new E('#editor')
      this.editor.config.zIndex = 100
      this.editor.config.uploadImgServer = this.upUrl
      this.editor.config.uploadFileName = 'file'
      this.editor.config.uploadImgHeaders = this.upHeaders
      this.editor.config.uploadImgHooks = {
        customInsert: (insertImgFn, result) => {
           // Adapt to both standard response and direct DRF response
           if (result && result.path) {
             insertImgFn(result.path)
           } else if ((result.code === 200 || result.code === 201) && result.data) {
             insertImgFn(result.data.path || result.data.file)
           } else {
             this.$message.error('上传失败: ' + (result.msg || '未知错误'))
           }
        }
      }

      this.editor.config.uploadVideoServer = this.upUrl
      this.editor.config.uploadVideoName = 'file'
      this.editor.config.uploadVideoHeaders = this.upHeaders
      this.editor.config.uploadVideoHooks = {
        customInsert: (insertVideoFn, result) => {
           if (result && result.path) {
             insertVideoFn(result.path)
           } else if ((result.code === 200 || result.code === 201) && result.data) {
             insertVideoFn(result.data.path || result.data.file)
           } else {
             this.$message.error('上传失败: ' + (result.msg || '未知错误'))
           }
        }
      }

      this.editor.config.onchange = (html) => {
        this.temp.detail = html
      }
      this.editor.create()
    },
    handleDelete(row, index) {
        this.$confirm('确认删除该项目?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            deleteProject(row.id).then(() => {
                this.$notify({
                title: 'Success',
                message: '删除成功',
                type: 'success',
                duration: 2000
                })
                this.list.splice(index, 1)
            })
        })
    },
    handleAvatarSuccess(res, file) {
      this.temp.image = res.data.path
    },
    // Student Management Methods
    handleStudents(row) {
        this.currentProject = row;
        this.studentDialogVisible = true;
        this.getEnrolledStudents();
    },
    getEnrolledStudents() {
        getStudentProjects({ project: this.currentProject.id }).then(response => {
            this.studentList = response.data.results;
        })
    },
    openAddStudent() {
        this.addStudentDialogVisible = true;
        this.selectedStudentId = undefined;
        this.searchStudents('');
    },
    searchStudents(query) {
        getStudents({ search: query }).then(response => {
            this.allStudents = response.data.results;
        })
    },
    confirmAddStudent() {
        if (!this.selectedStudentId) {
            this.$message.warning('请选择学员');
            return;
        }
        createStudentProject({
            student: this.selectedStudentId,
            project: this.currentProject.id
        }).then(() => {
            this.$message.success('添加成功');
            this.addStudentDialogVisible = false;
            this.getEnrolledStudents();
            this.getList(); // Update student count
        }).catch(err => {
             // Already handled by request interceptor mostly, but duplicate error might occur
             if (err.response && err.response.data && err.response.data.non_field_errors) {
                 this.$message.error('该学员已报名此项目');
             }
        })
    },
    removeStudent(row) {
        this.$confirm('确认移除该学员?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            deleteStudentProject(row.id).then(() => {
                this.$message.success('移除成功');
                this.getEnrolledStudents();
                this.getList(); // Update student count
            })
        })
    },
    handleStudentStatusChange(row) {
        updateStudentProject(row.id, { status: row.status }).then(() => {
            this.$message.success('状态更新成功');
        }).catch(() => {
            this.$message.error('状态更新失败');
            this.getEnrolledStudents(); // Revert changes
        });
    }
  }
}
</script>