<template>
  <div class="page">
    <div class="page-content">
      <el-form label-position="top" :model="formData" :rules="rules" ref="form">
        <el-form-item label="作品描述：" prop="title">
          <el-input
            type="textarea"
            rows="6"
            v-model="formData.title"
            placeholder="添加作品描述，能让更多的人看到..."
            maxlength="300"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="上传视频：" prop="ossUrl">
          <SimpleOssUpload @success="onVideoUploadSuccess" :limit="1"></SimpleOssUpload>
          <el-input v-show="false" v-model="formData.ossUrl"></el-input>
        </el-form-item>
        <el-form-item label="抖音视频链接：" prop="linked">
          <el-input type="textarea" rows="3" v-model="formData.linked" placeholder="请添加抖音视频链接"></el-input>
        </el-form-item>
      </el-form>
      <div class="tip">
        <div class="title">温馨提示：</div>
        <div class="content">
          视频文件大小不超过8G，时长在30分钟以内；分辨率为720p（720x1280）及以上； 支持常用视频格式，推荐使用mp4、webm
        </div>
      </div>
      <div class="control">
        <div class="button publish" @click="onPublish">提交</div>
        <div class="button cancel" @click="onBack">取消</div>
      </div>
    </div>

    <!-- 已上传视频列表 -->
    <div class="line"></div>
    <div class="video-container" v-if="videoList.length > 0">
      <div class="title"><span>已上传</span>（{{ videoList.length }}个）</div>
      <div class="video-list">
        <div class="video" v-for="(item, index) in videoList" :key="index" @click="onPlay(item)">
          <div class="cover">
            <img :src="item.cover" alt="item.title" v-if="item.cover" />
            <video :src="item.ossUrl" crossorigin="anonlymous" v-else></video>
            <div class="name">
              <span>{{ item.title }}</span>
            </div>
            <div class="play"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提示框 -->
    <GeneralDialog
      v-model="promptDialog"
      title="提示"
      content="抱歉，最多只能上传3个视频！!"
      @confirm="promptDialog = false"
    ></GeneralDialog>

    <!-- 视频播放组件 -->
    <SimpleVideoPlayer :videoSrc="videoUrl" :description="description" ref="videoPlayer"></SimpleVideoPlayer>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getVideoBase64 } from '~/utils'
export default {
  layout: 'app-ross',
  data() {
    return {
      promptDialog: false,
      formData: {
        authUserId: '',
        authId: '',
        userName: '',
        title: '',
        ossName: '',
        cover: '',
        ossUrl: '',
        linked: '',
      },
      rules: {
        ossUrl: [{ required: true, message: '请上传视频', trigger: ['change'] }],
        linked: [{ required: true, message: '请填写抖音链接', trigger: ['blur'] }],
      },
      videoList: [],
      videoUrl: '',
      description: '',
    }
  },
  computed: {
    ...mapGetters(['routePrefix', 'userInfo', 'authUserId']),
  },
  created() {
    this.fetchVideoList()
  },
  methods: {
    // 获取当前机构已发布的视频列表
    async fetchVideoList() {
      try {
        const { clubUserId, mobile } = this.userInfo
        const res = await this.$http.api.fetchOwnerVideoList({
          mobile: mobile,
          clubUserId: clubUserId,
          authUserId: this.authUserId,
        })
        this.videoList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 发布视频
    async onPublish() {
      if (this.videoList.length >= 3) {
        this.promptDialog = true
        return
      }
      try {
        await this.$refs.form.validate()
        if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
          this.publishVideoSave()
          return
        }
        // 生成封面
        const imageUrl = process.env.EVN === 'development' ? '/flower.mp4' : this.formData.ossUrl
        const cover = await getVideoBase64(imageUrl)
        const file = new File([cover], 'cover.jpg', { type: 'image/jpeg' })
        const formData = new FormData()
        formData.append('file', file)
        const res = await fetch(`${process.env.BASE_URL}/wx/upload/image`, {
          method: 'post',
          body: formData,
        })
        const result = await res.json()
        this.formData.cover = result.data
        this.publishVideoSave()
      } catch (error) {
        console.log(error)
      }
    },

    // 保存视频
    async publishVideoSave() {
      try {
        const { authId, mobile } = this.userInfo
        this.formData.authId = authId
        this.formData.userName = mobile
        this.formData.authUserId = this.authUserId
        await this.$http.api.publishVideo(this.formData)
        this.$router.replace(`${this.routePrefix}/activity/challenge/message`)
      } catch (error) {
        console.log(error)
      }
    },

    // 视频上传成功
    onVideoUploadSuccess({ file, fileList }) {
      this.formData.ossUrl = file.url
      this.formData.ossName = file.uuid
    },

    // 返回
    onBack() {
      this.$router.back()
    },

    // 播放视频
    onPlay(row) {
      this.videoUrl = row.ossUrl
      this.description = row.title
      this.$refs.videoPlayer.open()
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form-item__label {
    font-size: 16px;
  }
  .el-textarea .el-input__count {
    bottom: -32px;
    background: transparent;
  }
}

::v-deep {
  .el-input.is-active .el-input__inner,
  .el-input__inner:focus,
  .el-textarea__inner:focus,
  .el-upload--picture-card:hover,
  .el-upload:focus {
    border-color: #f3920d;
  }
}

@media screen and (min-width: 768px) {
  .page {
    background: #fff;
    padding: 40px 0;

    .video-container {
      width: 568px;
      margin: 0 auto;
      margin-top: 100px;
      .title {
        font-size: 16px;
        color: #282828;
        margin-bottom: 16px;
      }

      .video-list {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-column-gap: 16px;
        grid-row-gap: 16px;

        .video {
          background: #fff;
          box-sizing: border-box;
          border: 1px solid #efefef;

          &:hover {
            .info {
              .club-name {
                color: #f3920d;
              }
            }
          }

          &:nth-child(4n) {
            margin-right: 0;
          }

          .cover {
            height: 248px;
            position: relative;

            video {
              display: block;
              width: 100%;
              height: 100%;
              background: #000;
            }

            img {
              display: block;
              width: 100%;
              height: 100%;
              background: #000;
            }

            .play {
              position: absolute;
              z-index: 2;
              width: 32px;
              height: 32px;
              background: url(~assets/theme-images/common/pc-icon-play.png) no-repeat center;
              background-size: 32px;
              left: 50%;
              top: 50%;
              transform: translate(-50%, -50%);
              cursor: pointer;
            }

            .name {
              display: flex;
              align-items: flex-end;
              width: 100%;
              height: 75px;
              padding: 17px 16px;
              box-sizing: border-box;
              position: absolute;
              left: 0;
              bottom: 0;
              background: linear-gradient(180deg, rgba(51, 51, 51, 0) 0%, #333333 100%);

              span {
                color: #fff;
                font-size: 14px;
                line-height: 20px;
                max-height: 40px;
                @include ellipsis(2);
              }
            }
          }
        }
      }
    }

    .page-content {
      width: 568px;
      margin: 0 auto;

      .tip {
        margin: 60px 0;
        font-size: 14px;
        line-height: 1.8;
        .title {
          color: #666666;
          margin-bottom: 8px;
        }
        .content {
          color: #f94b4b;
        }
      }

      .control {
        .button {
          width: 295px;
          height: 50px;
          margin: 0 auto;
          border-radius: 4px;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 16px;
          &.cancel {
            border: 1px solid #c2c2c2;
            color: #666666;
            margin-top: 16px;
          }
          &.publish {
            background: #f3920d;
            color: #fff;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  ::v-deep {
    .el-form-item__label {
      font-size: 3.4vw;
      line-height: 4.6vw;
    }
  }

  .page {
    background: #fff;
    padding: 8vw 0;

    .line {
      width: 100%;
      height: 3.2vw;
      background: #f1f1f1;
      margin: 7.2vw 0;
    }

    .video-container {
      padding: 0 3.2vw;
      .title {
        font-size: 3.4vw;
        color: #282828;
        margin-bottom: 4vw;
        span {
          font-weight: bold;
        }
      }
      .video-list {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-column-gap: 2.4vw;
        grid-row-gap: 2.4vw;
        .video {
          background: #fff;
          box-sizing: border-box;
          border: 0.1vw solid #efefef;

          &:hover {
            .info {
              .club-name {
                color: #f3920d;
              }
            }
          }

          &:nth-child(4n) {
            margin-right: 0;
          }

          .cover {
            height: 64.4vw;
            position: relative;

            // video {
            //   display: block;
            //   width: 100%;
            //   height: 100%;
            //   background: #000;
            // }

            img {
              display: block;
              width: 100%;
              height: 100%;
              background: #000;
            }

            .play {
              position: absolute;
              z-index: 2;
              width: 7.2vw;
              height: 7.2vw;
              background: url(~assets/theme-images/common/h5-icon-play.png) no-repeat center;
              background-size: 7.2vw;
              left: 50%;
              top: 50%;
              transform: translate(-50%, -50%);
              cursor: pointer;
            }

            .name {
              display: flex;
              align-items: flex-end;
              width: 100%;
              height: 16vw;
              padding: 4.4vw 3vw;
              box-sizing: border-box;
              position: absolute;
              left: 0;
              bottom: 0;
              background: linear-gradient(180deg, rgba(51, 51, 51, 0) 0%, #333333 100%);

              span {
                color: #fff;
                font-size: 3vw;
                line-height: 3.6vw;
                max-height: 7.2vw;
                @include ellipsis(2);
              }
            }
          }
        }
      }
    }

    .page-content {
      padding: 0 3.2vw;
      .tip {
        margin: 20vw 0 12vw;
        font-size: 3vw;
        line-height: 1.8;
        .title {
          color: #666666;
          margin-bottom: 8px;
        }
        .content {
          color: #f94b4b;
        }
      }

      .control {
        .button {
          height: 12vw;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 3.6vw;
          &.cancel {
            border: 0.1vw solid #c2c2c2;
            color: #666666;
            margin-top: 3.2vw;
          }
          &.publish {
            background: #f3920d;
            color: #fff;
          }
        }
      }
    }
  }
}
</style>
