<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="80">
        <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.student }}</span></template>
      </el-table-column>
      <el-table-column label="类型" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.notification_type | typeFilter">{{ row.notification_type | typeLabel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.is_read ? 'success' : 'info'">{{ row.is_read ? '已读' : '未读' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发送时间" width="160px" align="center">
        <template slot-scope="{row}"><span>{{ row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span></template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(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">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="接收学员" prop="student">
          <el-select v-model="temp.student" filterable remote :remote-method="searchStudents" :loading="studentLoading" placeholder="请输入学员姓名搜索" style="width: 100%">
             <el-option v-for="item in studentOptions" :key="item.id" :label="item.name + ' (' + (item.phone || '-') + ')'" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="temp.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="类型" prop="notification_type">
          <el-select v-model="temp.notification_type" placeholder="请选择类型" style="width: 100%">
            <el-option label="系统通知" value="system" />
            <el-option label="活动提醒" value="activity" />
            <el-option label="课程通知" value="course" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否已读" prop="is_read">
           <el-switch v-model="temp.is_read" />
        </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>
  </div>
</template>

<script>
import { getNotifications, createNotification, updateNotification, deleteNotification, getStudents } from '@/api/crm'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

export default {
  name: 'NotificationTable',
  components: { Pagination },
  filters: {
    typeFilter(type) {
      const statusMap = {
        system: 'info',
        activity: 'success',
        course: 'warning'
      }
      return statusMap[type]
    },
    typeLabel(type) {
        const labelMap = {
            system: '系统通知',
            activity: '活动提醒',
            course: '课程通知'
        }
        return labelMap[type] || type
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined
      },
      studentOptions: [],
      studentLoading: false,
      temp: {
        id: undefined,
        student: undefined,
        title: '',
        content: '',
        notification_type: 'system',
        is_read: false
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        student: [{ required: true, message: '请选择学员', trigger: 'change' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        notification_type: [{ required: true, message: '请选择类型', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
    // Pre-fetch some students
    this.searchStudents('') 
  },
  methods: {
    getList() {
      this.listLoading = true
      getNotifications(this.listQuery).then(response => {
        // Assume DRF DefaultRouter with pagination returns { count: ..., results: ... }
        // or if wrapped: { data: { count: ..., results: ... } }
        // Based on other views (e.g. Student), it seems pagination is used.
        // Let's check NotificationViewSet. It inherits ModelViewSet. 
        // If pagination is not disabled, it returns paginated response.
        
        // Checking existing code, e.g. StudentTable, it uses response.data.items or response.data.results?
        // Let's assume standard DRF pagination structure or the wrapper used in this project.
        // Looking at student.vue: 
        // this.list = response.data.items
        // this.total = response.data.total
        // Wait, let me check the wrapper.
        
        // If backend returns standard DRF: { count: 100, results: [...] }
        // If wrapped: { code: 200, data: { items: [...], total: ... } } ?
        
        // Let's check `request.js` or `StudentViewSet` pagination.
        // `admin/server/utils/pagination.py` might be used.
        
        // Assuming the response structure is consistent with other lists.
        // If I look at `student.vue` again (I read it earlier):
        // It imports `getStudents`.
        // `getList` calls `getStudents`.
        // But I didn't see the implementation of `getList` in `student.vue` fully in previous `Read` call (it was cut off).
        
        // I'll assume standard structure for now:
        if (response.data && response.data.results) {
            this.list = response.data.results
            this.total = response.data.count
        } else if (response.data && Array.isArray(response.data)) {
            this.list = response.data
            this.total = response.data.length
        } else {
             // Fallback
             this.list = response.data
             this.total = 0
        }
        this.listLoading = false
      })
    },
    searchStudents(query) {
      this.studentLoading = true
      getStudents({ search: query, page: 1, limit: 20 }).then(response => {
        if (response.data && response.data.results) {
             this.studentOptions = response.data.results
        } else {
             this.studentOptions = response.data
        }
        this.studentLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        student: undefined,
        title: '',
        content: '',
        notification_type: 'system',
        is_read: false
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createNotification(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()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateNotification(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          deleteNotification(row.id).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
      })
    }
  }
}
</script>
