<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="学员信息" align="center" width="180">
        <template slot-scope="{row}">
          <div style="display:flex; align-items:center;">
              <img v-if="row.student_avatar" :src="row.student_avatar" style="width:30px;height:30px;border-radius:50%;margin-right:5px;">
              <div style="display:flex; flex-direction:column; align-items:flex-start;">
                <span>{{ row.student_name }}</span>
                <span style="font-size:12px; color:#999;" v-if="row.student_teaching_center">{{ row.student_teaching_center }}</span>
                <span style="font-size:12px; color:#999;" v-if="row.student_company_name">{{ row.student_company_name }}</span>
              </div>
          </div>
        </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.date }}</span></template>
      </el-table-column>
      <el-table-column label="证书图片" width="100px" align="center">
        <template slot-scope="{row}"><img :src="row.image" width="50" height="50" style="object-fit:cover"></template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <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" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 500px; margin-left:50px;">
        <el-form-item label="选择学员" prop="student">
            <el-select v-model="temp.student" filterable remote :remote-method="searchStudents" placeholder="请输入姓名或电话搜索" style="width: 100%" @change="handleStudentChange">
                <el-option v-for="item in allStudents" :key="item.id" :label="item.name + ' (' + item.phone + ')'" :value="item.id" />
            </el-select>
            <div v-if="selectedStudentOrganization" style="font-size: 12px; color: #606266; margin-top: 5px; background-color: #f4f4f5; padding: 5px 10px; border-radius: 4px;">
                <i class="el-icon-office-building"></i> 所属机构: {{ selectedStudentOrganization }}
            </div>
        </el-form-item>
        <el-form-item label="荣誉标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="获得日期" prop="date">
           <el-date-picker v-model="temp.date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <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="temp.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="荣誉描述" prop="description">
          <el-input v-model="temp.description" type="textarea" :rows="3" />
        </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>

<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 { getHonors, createHonor, updateHonor, deleteHonor, getStudents } from '@/api/crm'
import Pagination from '@/components/Pagination'
import { upUrl, upHeaders } from "@/api/file"

export default {
  name: 'HonorTable',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined
      },
      temp: {
        id: undefined,
        student: undefined,
        title: '',
        image: 'https://images.unsplash.com/photo-1579548122080-c35fd6820ecb',
        date: new Date().toISOString().slice(0, 10),
        description: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        student: [{ required: true, message: '请选择学员', trigger: 'change' }],
        title: [{ required: true, message: '请输入荣誉标题', trigger: 'blur' }],
        date: [{ required: true, message: '请选择日期', trigger: 'change' }]
      },
      upUrl: upUrl(),
      upHeaders: upHeaders(),
      allStudents: [],
      selectedStudentOrganization: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getHonors(this.listQuery).then(response => {
        this.list = response.data.results
        this.total = response.data.count
        this.listLoading = false
      })
    },
    searchStudents(query) {
        getStudents({ search: query, page: 1, limit: 20 }).then(response => {
            this.allStudents = response.data.results
        })
    },
    handleStudentChange(val) {
        const student = this.allStudents.find(item => item.id === val)
        if (student) {
            this.selectedStudentOrganization = student.teacher_name || ''
        } else {
            this.selectedStudentOrganization = ''
        }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        student: undefined,
        title: '',
        image: 'https://images.unsplash.com/photo-1579548122080-c35fd6820ecb',
        date: new Date().toISOString().slice(0, 10),
        description: ''
      }
      this.allStudents = []
      this.selectedStudentOrganization = ''
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.searchStudents('')
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createHonor(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // Pre-fetch the student info for the select
      if (row.student) {
          // Use student_name and student_phone from row to populate the select option
          this.allStudents = [{
              id: row.student,
              name: row.student_name,
              phone: row.student_phone || '',
              teacher_name: row.student_teaching_center
          }]
          this.selectedStudentOrganization = row.student_teaching_center
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateHonor(tempData.id, tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
        this.$confirm('确认删除该荣誉吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            deleteHonor(row.id).then(() => {
                this.$notify({
                title: 'Success',
                message: 'Delete Successfully',
                type: 'success',
                duration: 2000
                })
                this.list.splice(index, 1)
            })
        })
    },
    handleAvatarSuccess(res, file) {
        this.temp.image = res.data.path
    }
  }
}
</script>
