<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="100px" align="center">
        <template slot-scope="{row}">
            <img :src="row.cover_image" width="50" height="50" style="object-fit:cover">
        </template>
      </el-table-column>
      <el-table-column label="视频链接" min-width="200px" align="center">
        <template slot-scope="{row}">
            <a v-if="row.video_url" :href="row.video_url" target="_blank" style="color: #409EFF;">{{ row.video_url }}</a>
            <span v-else style="color: #909399;">无视频</span>
        </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="状态" class-name="status-col" width="100">
        <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="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="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="封面图片" prop="cover_image">
             <el-upload
                class="avatar-uploader"
                :action="upUrl"
                :headers="upHeaders"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
                :before-upload="beforeImageUpload">
                <img v-if="temp.cover_image" :src="temp.cover_image" class="avatar" style="width: 100px; height: 100px; object-fit: cover;">
                <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; width: 100px; height: 100px; line-height: 100px; text-align: center;"></i>
             </el-upload>
             <div style="font-size: 12px; color: #999;">点击上传封面图片</div>
        </el-form-item>
        <el-form-item label="视频文件" prop="video_url">
           <el-upload
              class="upload-demo"
              :action="upUrl"
              :headers="upHeaders"
              :on-success="handleVideoSuccess"
              :before-upload="beforeVideoUpload"
              :limit="1"
              :file-list="videoFileList">
              <el-button size="small" type="primary">点击上传视频</el-button>
              <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
            </el-upload>
            <div v-if="temp.video_url" style="margin-top: 10px;">
                <a :href="temp.video_url" target="_blank" style="color: #409EFF;">查看当前视频</a>
            </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="temp.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="是否启用" prop="is_active">
          <el-switch v-model="temp.is_active" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" type="textarea" :rows="4" placeholder="请输入描述" />
        </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 { getShowcases, createShowcase, updateShowcase, deleteShowcase } from '@/api/crm'
import Pagination from '@/components/Pagination'
import { upUrl, upHeaders } from "@/api/file"

export default {
  name: 'ShowcaseTable',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined
      },
      temp: {
        id: undefined,
        title: '',
        // student: undefined, // Removed
        cover_image: 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3',
        video_url: '',
        description: '',
        sort_order: 0,
        is_active: true
      },
      videoFileList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        cover_image: [{ required: true, message: '请上传封面图片', trigger: 'blur' }]
      },
      upUrl: upUrl(),
      upHeaders: upHeaders()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getShowcases(this.listQuery).then(response => {
        this.list = response.data.results
        this.total = response.data.count
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        // student: undefined,
        cover_image: 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3',
        video_url: '',
        description: '',
        sort_order: 0,
        is_active: true
      }
      this.videoFileList = []
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // Debug log to check data before sending
          console.log('Creating showcase with data:', this.temp);

          createShowcase(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

      if (this.temp.video_url) {
          this.videoFileList = [{name: '当前视频', url: this.temp.video_url}]
      } else {
          this.videoFileList = []
      }

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateShowcase(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(() => {
            deleteShowcase(row.id).then(() => {
                this.$notify({
                title: 'Success',
                message: 'Delete Successfully',
                type: 'success',
                duration: 2000
                })
                this.list.splice(index, 1)
            })
        })
    },
    handleCoverSuccess(res, file) {
        if (res.data && res.data.path) {
             this.temp.cover_image = res.data.path
        } else {
             this.temp.cover_image = res.path || res.file
        }
    },
    beforeImageUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    handleVideoSuccess(res, file) {
        console.log('Video upload raw response:', res);

        // FileViewSet.perform_create saves the absolute URL into 'path' field of the File model.
        // FileSerializer returns all fields including 'path'.

        // Use data from res directly if it exists, otherwise check for nested data structure
        const data = res.data || res;

        if (data.path) {
             this.temp.video_url = data.path
        } else if (data.file) {
             // Fallback if path is missing (unlikely with current backend logic)
             this.temp.video_url = data.file
        } else if (typeof data === 'string' && data.startsWith('http')) {
             // Sometimes it might just return the URL string directly
             this.temp.video_url = data
        }

        console.log('Set video_url to:', this.temp.video_url);
        this.videoFileList = [{name: file.name, url: this.temp.video_url}]
    },
    beforeVideoUpload(file) {
        const isVideo = file.type.indexOf('video') !== -1;
        // const isLt50M = file.size / 1024 / 1024 < 50;

        if (!isVideo) {
            this.$message.error('只能上传视频文件!');
        }
        // if (!isLt50M) {
        //     this.$message.error('视频大小不能超过 50MB!');
        // }
        // return isVideo && isLt50M;
        return isVideo;
    }
  }
}
</script>
