<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div>
      <el-input v-model="searchParams.search_name" placeholder="请输入教程信息" size="small" style="width:250px" />
      <el-select v-model="searchParams.type" placeholder="请选择" size="small">
        <el-option label="视频教程" value="1" />
        <el-option label="图文教程" value="2" />
      </el-select>
      <el-button
        type="primary"
        size="small"
        @click="searchParams.page_index = 1;getGuideList()"
      >
        查询
      </el-button>
      <el-button type="primary" icon="el-icon-plus" size="small" @click="visible.course = true; editFlag = false">添加</el-button>
    </div>
    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        prop="title"
        label="标题"
        align="center"
      />
      <el-table-column
        prop="type"
        label="类型"
        align="center"
      >
        <template slot-scope="{ row }">
          {{ row.type === 1 ? '视频教程' : '图文教程' }}
        </template>
      </el-table-column>
      <el-table-column
        label="教程详情"
        align="center"
      >
        <template slot-scope="{ row }">
          <template v-if="row.type === 1">
            <el-button type="text" @click="handleSeeVideo(row)">查看视频</el-button>
          </template>
          <template v-else>
            <el-image
              style="width:60px;height:60px"
              :src="row.url"
              fit="cover"
            />
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="上传时间"
        align="center"
      />
      <el-table-column
        prop="status"
        label="状态"
        align="center"
        width="150"
      >
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">{{ row.status === 1 ? '正常' : '已禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleEdit(row)">修改</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
          <el-button type="text" @click="handleDisable(row)">{{ row.status === 1 ? '禁用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="batch-container">
      <!-- 分页 -->
      <pagination
        :total="tableTotal"
        :limit="searchParams.page_size"
        :page="searchParams.page_index"
        style="margin-top:0"
        @pagination="changePagination"
        @update:limit="changePagination"
      />
    </div>
    <!-- 上传 -->
    <el-dialog
      title="添加"
      :visible.sync="visible.course"
    >
      <el-form ref="courseForm" label-width="80px" :model="course" :rules="courseRules">
        <el-form-item label="标题:" prop="title">
          <el-input v-model="course.title" />
        </el-form-item>
        <el-form-item label="类型:" prop="type">
          <el-select v-model="course.type" placeholder="请选择" size="small">
            <el-option label="视频教程" value="1" />
            <el-option label="图文教程" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件上传:">
          <el-upload
            class="upload-demo"
            drag
            action="http://api.admin.app.jiuweiyun.cn/api/guide/uploadguidefiles"
            :before-upload="beforeUploadVideo"
            :on-progress="uploadVideoProcess"
            :show-file-list="false"
            :on-success="uploadVideoSuccess"
            name="file"
            :data="uploadParams"
            :headers="uploadHeaders"
          >
            <div v-if="course.type === '1'">
              <div v-if="!videoFlag">
                <video v-if="course.url !==''" :src="course.url" class="avatar" controls="controls">您的浏览器不支持视频播放</video>
                <div v-else>
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </div>
              </div>
              <el-progress v-if="videoFlag" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;" />
            </div>
            <div v-else>
              <div v-if="!videoFlag">
                <img v-if="course.url !==''" :src="course.url" class="avatar">
                <div>
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </div>
              </div>
              <el-progress v-if="videoFlag" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;" />
            </div>
            <div slot="tip" class="el-upload__tip">
              <template v-if="course.type === '1'">只能上传视频文件，且不超过100MB</template>
              <template v-else>上传jpg/png图片</template>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="course.url !== ''" label="链接地址:">
          <el-input v-model="course.url" disabled />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input
            v-model="course.contents"
            type="textarea"
            :rows="4"
            placeholder="备注信息"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleUpload">{{ editFlag ? '修改' : '添加' }}</el-button>
          <el-button size="small" @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看视频 -->
    <el-dialog
      title="视频教程"
      :visible.sync="visible.video"
    >
      <video :src="seeVideoInfoUrl" class="avatar" controls="controls">您的浏览器不支持视频播放</video>
    </el-dialog>
  </div>
</template>
<script>
// api
import { getGuideList, editGuide, addGuide, disableGuide, deleteGuide } from '@/api/activity/tutorial'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      searchParams: {
        page_index: 1,
        page_size: 10,
        search_name: '',
        type: '1'
      },
      table: [],
      tableTotal: 0,
      visible: {
        course: false,
        video: false
      },
      course: {
        title: '',
        url: '',
        type: '1',
        contents: '',
        id: ''
      },
      courseRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      videoFlag: false,
      videoUploadPercent: 0,
      uploadHeaders: {
        'authorization': 'Bearer ' + getToken()
      },
      seeVideoInfoUrl: '',
      editFlag: false,
      loadingFull: false
    }
  },
  computed: {
    uploadParams() {
      return {
        type: this.course.type
      }
    }
  },
  watch: {
    'course.type'(newVal, oldVal) {
      this.videoFlag = false
      this.videoUploadPercent = 0
      this.course.url = ''
    }
  },
  created() {
    this.getGuideList()
  },
  methods: {
    // 获取列表
    async getGuideList() {
      this.loadingFull = true
      try {
        const res = await getGuideList(this.searchParams)
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取教程列表失败: ${e}`)
      }
      this.loadingFull = false
    },
    // 删除
    async deleteGuide(id) {
      try {
        const res = await deleteGuide({ id })
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          this.getGuideList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`删除教程失败: ${e}`)
      }
    },
    // 禁用
    async disableGuide(id) {
      try {
        const res = await disableGuide({ id })
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          this.getGuideList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('禁用教程失败!!')
      }
    },
    // 添加
    handleUpload() {
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          if (!this.editFlag) {
            const { title, type, url, contents } = this.course
            this.addGuide({
              title,
              type,
              url,
              contents
            })
          } else {
            this.editGuide(this.course)
          }
        } else {
          return false
        }
      })
    },
    // 添加
    async addGuide(data) {
      try {
        const res = await addGuide(data)
        const { code, message } = res
        if (code === 200) {
          this.handleClose()
          this.getGuideList()
          this.$message.success(message)
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('上传教程失败!!')
      }
    },
    // 关闭弹窗
    handleClose() {
      this.$refs.courseForm.resetFields()
      this.editFlag = false
      this.course.id = ''
      this.course.url = ''
      this.course.title = ''
      this.course.type = '1'
      this.course.contents = ''
      this.videoFlag = false
      this.videoUploadPercent = 0
      this.visible.course = false
    },
    // 删除
    handleDelete(row) {
      const { id, title } = row
      this.$confirm(`确认删除教程: ${title} 吗?`, '删除教程', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteGuide(id)
      })
    },
    // 禁用启用
    handleDisable(row) {
      const { id, title, status } = row
      const msg = status === 1 ? '禁用' : '启用'
      this.$confirm(`确认${msg}教程: ${title} 吗?`, `${msg}教程`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.disableGuide(id)
      })
    },
    // 上传前验证
    beforeUploadVideo(file) {
      if (this.course.type === '1') {
        const isLt100M = file.size / 1024 / 1024 < 100
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) === -1) {
          this.$message.error('请上传正确的视频格式')
          return false
        }
        if (!isLt100M) {
          this.$message.error('上传视频大小不能超过100MB')
          return false
        }
      } else {
        if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(file.type) === -1) {
          this.$message.error('请上传正确的图片格式')
          return false
        }
      }
    },
    // 上传进度显示
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true
      this.videoUploadPercent = Number(file.percentage.toFixed(0))
    },
    // 上传成功
    uploadVideoSuccess(res, file) {
      this.videoFlag = false
      this.videoUploadPercent = 0
      const { code, message } = res
      if (code === 200) {
        const { data } = res
        this.course.url = data
      } else {
        this.$message.error(message)
      }
    },
    // 查看视频
    handleSeeVideo(row) {
      const { url } = row
      this.seeVideoInfoUrl = url
      this.visible.video = true
    },
    // 修改
    handleEdit(row) {
      const { title, type, url, id, contents } = row
      this.editFlag = true
      this.course.type = String(type)
      this.course.title = title
      this.course.url = url
      this.course.contents = contents
      this.course.id = id
      this.visible.course = true
    },
    // 修改
    async editGuide(data) {
      try {
        const res = await editGuide(data)
        const { code, message } = res
        if (code === 200) {
          this.handleClose()
          this.getGuideList()
          this.$message.success(message)
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('修改教程失败!!')
      }
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getGuideList()
    }
  }
}
</script>
<style lang="scss" scoped>
    .tableBorder{
        border: 1px solid #EBEEF5;
        margin: 20px 0;
    }
    .avatar{
        display: block;
        width: 100%;
        height: 100%;
    }
</style>
