<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>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleClearAll">
        清空全部
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column label="城市" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.city || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已报项目" align="center" min-width="200">
        <template slot-scope="{row}">
            <div v-if="row.enrolled_projects && row.enrolled_projects.length > 0" style="text-align: left;">
                <div v-for="(project, index) in row.enrolled_projects" :key="index" style="margin-bottom: 5px; font-size: 12px;">
                    <span style="font-weight: 500;">{{ project.project_title }}</span>
                    <el-tag size="mini" :type="project.status | projectStatusFilter" style="margin-left: 5px; transform: scale(0.9);">
                        {{ project.status_display }}
                    </el-tag>
                </div>
            </div>
            <span v-else style="color: #999; font-size: 12px;">暂无项目</span>
        </template>
      </el-table-column>
      <el-table-column label="微信信息" width="180px" align="center">
        <template slot-scope="{row}">
          <div style="display: flex; align-items: center; justify-content: center;">
            <img v-if="row.avatar" :src="row.avatar" style="width: 40px; height: 40px; border-radius: 50%; margin-right: 10px;">
            <div style="display:flex; flex-direction:column; align-items:flex-start;">
                <span>{{ row.wechat_nickname || '-' }}</span>
                <span style="font-size:12px; color:#999;" v-if="row.openid">{{ row.openid.slice(0,6) }}...</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="关联教学中心" min-width="120px" align="center">
        <template slot-scope="{row}">
            <span>{{ row.teacher_name || row.teacher || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司名称" min-width="120px" align="center">
        <template slot-scope="{row}">
            <span>{{ row.company_name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职位" min-width="100px" align="center">
        <template slot-scope="{row}">
            <span>{{ row.position || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status_display }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="success" size="mini" @click="openAssign(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="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="temp.age" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="temp.city" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" />
        </el-form-item>
        <el-form-item label="头像URL" prop="avatar">
          <el-input v-model="temp.avatar" />
        </el-form-item>
        <el-form-item label="微信唯一标识" prop="openid">
          <el-input v-model="temp.openid" placeholder="OpenID" />
        </el-form-item>
        <el-form-item label="关联教学中心" prop="teacher">
          <el-select v-model="temp.teacher" 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-form-item label="公司名称" prop="company_name">
          <el-input v-model="temp.company_name" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="temp.position" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="普通用户" value="ordinary" />
            <el-option label="意向用户" value="intention" />
            <el-option label="在读" value="reading" />
            <el-option label="毕业" value="graduated" />
          </el-select>
        </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="assignDialogVisible">
      <el-form label-position="left" label-width="90px" style="width: 420px; margin-left:50px;">
        <el-form-item label="选择优惠券">
          <el-select v-model="selectedCouponId" placeholder="请选择" filterable style="width: 300px;">
            <el-option
              v-for="c in coupons"
              :key="c.id"
              :label="c.title + '（'+ c.amount + c.unit +'）'"
              :value="c.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAssign">确认分配</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStudents, createStudent, updateStudent, deleteStudent, clearStudents, getCoupons, assignCouponToStudent, getTeachers, getTeachingCenters } from '@/api/crm'
import Pagination from '@/components/Pagination'

export default {
  name: 'StudentTable',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        ordinary: 'info',
        intention: 'warning',
        reading: 'success',
        graduated: ''
      }
      return statusMap[status]
    },
    projectStatusFilter(status) {
      const statusMap = {
        enrolled: '',
        studying: 'success',
        graduated: 'warning',
        finished: 'info'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined
      },
      teachers: [],
      teachingCenters: [],
      temp: {
        id: undefined,
        name: '',
        phone: '',
        age: undefined,
        city: '',
        address: '',
        avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde',
        openid: '',
        teacher: undefined,
        company_name: '',
        position: '',
        status: 'ordinary'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
      },
      assignDialogVisible: false,
      selectedCouponId: undefined,
      coupons: [],
      currentStudentId: undefined
    }
  },
  created() {
    this.getList()
    this.getTeachers()
    this.getTeachingCenters()
  },
  methods: {
    getList() {
      this.listLoading = true
      getStudents(this.listQuery).then(response => {
        this.list = response.data.results
        this.total = response.data.count
        this.listLoading = false
      })
    },
    getTeachers() {
      getTeachers().then(response => {
        this.teachers = response.data.results || response.data
      })
    },
    getTeachingCenters() {
      getTeachingCenters().then(response => {
        this.teachingCenters = response.data.results || response.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        phone: '',
        age: undefined,
        city: '',
        address: '',
        avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde',
        openid: '',
        teacher: undefined,
        company_name: '',
        position: '',
        status: 'ordinary'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createStudent(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)
          updateStudent(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            const msg = (error && error.response && error.response.data && error.response.data.msg) || (error && error.message) || '更新失败'
            this.$notify({
              title: 'Error',
              message: msg,
              type: 'error',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStudent(row.id).then(() => {
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          // this.list.splice(index, 1)
          this.getList()
        }).catch(error => {
          console.error('Delete failed:', error)
          const msg = (error && error.response && error.response.data && error.response.data.msg) || (error && error.message) || '删除失败'
          this.$notify({
            title: 'Error',
            message: msg,
            type: 'error',
            duration: 2000
          })
        })
      }).catch(() => {
        // Cancelled
      })
    },
    handleClearAll() {
      this.$confirm('此操作将永久删除所有学员数据且不可恢复，是否继续？', '高风险操作', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$prompt('为防止误操作，请输入“清空”确认', '二次确认', {
          confirmButtonText: '确认清空',
          cancelButtonText: '取消',
          inputPattern: /^清空$/,
          inputErrorMessage: '请输入“清空”'
        }).then(() => {
          clearStudents().then(() => {
            this.$notify({
              title: 'Success',
              message: '已清空全部学员',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            const msg = (error && error.response && error.response.data && error.response.data.msg) || (error && error.message) || '清空失败'
            this.$notify({
              title: 'Error',
              message: msg,
              type: 'error',
              duration: 2000
            })
          })
        }).catch(() => {})
      }).catch(() => {})
    },
    openAssign(row) {
      this.currentStudentId = row.id
      this.assignDialogVisible = true
      this.selectedCouponId = undefined
      this.getCoupons()
    },
    getCoupons() {
      getCoupons({ status: 'available' }).then(response => {
        this.coupons = response.data.results
      })
    },
    confirmAssign() {
      if (!this.selectedCouponId) {
        this.$message.warning('请选择优惠券')
        return
      }
      assignCouponToStudent(this.currentStudentId, this.selectedCouponId).then(() => {
        this.$notify({
          title: 'Success',
          message: '分配成功',
          type: 'success',
          duration: 2000
        })
        this.assignDialogVisible = false
      })
    }
  }
}
</script>
