<template>
  <div class="app-container">
    <div class="filter-container activity">
      <div class="filter-control">
        <span>活动时间:</span>
        <el-date-picker
          v-model="activityFormData.time"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled="activityFormData.status === 1"
        />
      </div>
      <div class="filter-control">
        <span>活动状态:</span>
        <el-switch
          v-model="activityFormData.status"
          el-switch
          :active-value="1"
          :inactive-value="0"
          @change="onUpdateActivityStatus"
        />
      </div>
    </div>
    <el-divider />
    <div class="filter-container">
      <div class="filter-control">
        <span>登录账号:</span>
        <el-input v-model="listQuery.mobile" placeholder="登录账号" @keyup.enter.native="getList" />
      </div>
      <div class="filter-control">
        <span>机构类型:</span>
        <el-select v-model="listQuery.authenticationStatus" placeholder="机构类型" clearable @change="getList">
          <el-option label="全部" value="" />
          <el-option label="未认证机构" :value="0" />
          <el-option label="已认证机构" :value="1" />
        </el-select>
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList">查询</el-button>
      </div>
    </div>
    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      header-row-class-name="tableHeader"
    >
      <el-table-column label="序号" :index="indexMethod" align="center" width="80" type="index" />
      <el-table-column label="登录账号" align="center" prop="userName" width="240" />
      <el-table-column label="机构名称" align="center" prop="authParty">
        <template slot-scope="{ row }">
          <span v-if="row.authParty">{{ row.authParty }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="机构类型" align="center" width="160">
        <template slot-scope="{ row }">
          <span v-if="row.authId" class="status success">已认证机构</span>
          <span v-else class="status danger" title="当前机构未认证">未认证机构</span>
        </template>
      </el-table-column>
      <el-table-column label="机构资质" align="center" width="160">
        <template slot-scope="{ row }">
          <span
            v-if="!row.authId"
            class="status success cursor-pointer"
            @click="onShowCertification(row)"
          >查看资质</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" width="160">
        <template slot-scope="{ row }">
          {{ row.contestDate | formatTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240">
        <template slot-scope="{ row }">
          <permission-button size="mini" type="primary" @click="onShowVideoList(row)">视频列表</permission-button>
          <permission-button size="mini" type="primary" @click="onRemoveClub(row)">删除</permission-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看机构资质 -->
    <el-dialog title="机构资质" :visible.sync="certificationDialog" width="600px" center :close-on-click-modal="false">
      <img :src="certificationUrl" class="certification">
    </el-dialog>

    <el-dialog title="视频列表" :visible.sync="showVideoListDialog" width="1000px" center :close-on-click-modal="false">
      <VideoList :list="videoList" :is-loading="videoListLoading" @delete="onDeleteVideo" @preview="onPlayVideo" />
      <!-- 视频播放 -->
      <el-dialog
        title="视频播放"
        :visible.sync="videoDialog"
        width="800px"
        center
        :close-on-click-modal="false"
        append-to-body
      >
        <video class="video-play" :src="videoUrl" controls />
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteClub,
  deleteClubVideo,
  fetchClubVideoList,
  fetchDouyinActivityStatus,
  fetchSignInClubList,
  updateDouyinActivityStatus
} from '@/api/activity'
import VideoList from '../components/video-list.vue'

export default {
  name: 'ChallengeVideoList',
  components: {
    VideoList
  },
  data() {
    return {
      listQuery: {
        status: '',
        mobile: '',
        authenticationStatus: '',
        pageNum: 1,
        pageSize: 10
      },
      listLoading: false,
      list: [],
      // 活动表单数据
      activityFormData: {
        time: [],
        status: 0
      },
      // 机构资质
      certificationDialog: false,
      certificationUrl: '',
      // 机构视频列表
      videoList: [],
      videoListLoading: false,
      showVideoListDialog: false,
      currentClub: null,
      // 视频预览
      videoDialog: false,
      videoUrl: ''
    }
  },
  created() {
    this.initPage()
  },
  activated() {
    this.initPage()
  },
  methods: {
    initPage() {
      this.getList()
      this.fetchActivityStatus()
    },

    // 获取参赛机构列表
    getList() {
      this.list = []
      this.listQuery.pageNum = 1
      this.fetchClubList()
    },

    // 获取参赛机构列表
    async fetchClubList() {
      try {
        this.listLoading = true
        const res = await fetchSignInClubList(this.listQuery)
        this.list = res.data.list
        this.listLoading = false
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },

    // 删除参赛机构操作
    async onRemoveClub(row) {
      try {
        await this.$confirm('确定删除该机构用户吗？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          showClose: false
        })
        this.deleteClub(row)
      } catch (error) {
        this.$message.info('已取消操作！')
        console.log(error)
      }
    },

    // 删除参赛机构操作
    async deleteClub(row) {
      try {
        await deleteClub({ id: row.id })
        this.fetchClubList()
        this.$message.success('机构删除成功')
      } catch (error) {
        console.log(error)
        this.$message.error('机构删除失败')
      }
    },

    // 获取机构上传视频列表
    async onShowVideoList(row) {
      try {
        this.currentClub = row
        const res = await fetchClubVideoList({ mobile: row.userName, clubUserId: '' })
        this.videoList = res.data
        if (this.videoList.length === 0) {
          this.$message.warning('当前机构未上传视频')
          return
        }
        this.showVideoListDialog = true
      } catch (error) {
        console.log(error)
      }
    },

    // 删除机构已上传的视频
    async onDeleteVideo(row) {
      try {
        await this.$confirm('确定删除该机构用户上传视频吗？删除后，抖音视频挑战首页将不再显示该视频！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          showClose: false
        })
        this.deleteVideo(row)
      } catch (error) {
        this.$message.info('已取消操作！')
        console.log(error)
      }
    },

    // 视频删除
    async deleteVideo(row) {
      try {
        await deleteClubVideo({ id: row.id })
        this.$message.success('视频删除成功')
        this.onShowVideoList(this.currentClub)
      } catch (error) {
        console.log(error)
        this.$message.success('视频删除失败')
      }
    },

    // 播放视频
    onPlayVideo(row) {
      this.videoDialog = true
      this.videoUrl = row.ossUrl
    },

    // 获取活动状态
    async fetchActivityStatus() {
      try {
        const res = await fetchDouyinActivityStatus()
        if (!res.data) return
        const { startTime, endTime } = res.data
        if (startTime && endTime) {
          this.activityFormData.time = [startTime, endTime]
        }
        this.activityFormData.status = res.data.status
      } catch (error) {
        console.log(error)
      }
    },

    // 验证活动时间
    checkActivityTime(startTime, endTime) {
      startTime = new Date(startTime).getTime()
      endTime = new Date(endTime).getTime()
      const nowTime = Date.now()
      if (startTime < nowTime) {
        return 1
      }
      if (endTime < startTime) {
        return 2
      }
      if (endTime < nowTime) {
        return 3
      }
    },

    // 更新活动时间状态
    async onUpdateActivityStatus(value) {
      let flag = -1
      const dialog = {
        0: '请先设置活动时间后，再来开启活动按钮',
        1: '活动开始时间不能小于当前时间',
        2: '活动结束时间不能小于活动开始时间',
        3: '你设置的活动时间已失效，请重新设置有效活动时间后，再来开启活动按钮'
      }
      if (!this.activityFormData.time) {
        flag = 0
      } else {
        const [start, end] = this.activityFormData.time
        flag = this.checkActivityTime(start, end)
      }
      if (flag > -1 && value === 1) {
        this.$confirm(dialog[flag], '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          showClose: false
        })
          .then(() => {
            this.activityFormData.status = 0
          })
          .catch(() => {
            this.activityFormData.status = 0
          })
        return
      }
      try {
        const {
          status,
          time: [startTime, endTime]
        } = this.activityFormData
        await updateDouyinActivityStatus({
          startTime,
          endTime,
          status
        })
        this.$message.success(`活动已${status ? '开启' : '关闭'}`)
      } catch (error) {
        console.log(error)
      }
    },

    // 产看资质
    onShowCertification(row) {
      this.certificationUrl = row.licenseOssUrl
      this.certificationDialog = true
    },

    // 表格索引
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.cursor-pointer {
  cursor: pointer;
  user-select: none;
}

.activity {
  .filter-control {
    margin-bottom: 0;
  }
}

.el-divider {
  margin: 12px 0;
}

.el-dialog {
  .control {
    text-align: right;
  }

  .certification {
    width: 100%;
    display: block;
  }
}

.video-play {
  display: block;
  width: 100%;
  height: 480px;
  background: #666;
}
</style>
