<template>
  <ai-detail class="add-video">
    <template slot="title">
      <ai-title :title="isEdit?'编辑视频':'发布视频'" :isShowBack="true" :isShowBottomBorder="true"
                @onBackClick="$emit('goBack')"></ai-title>
    </template>
    <template slot="content">
      <ai-card title="发布视频">
        <template #content>
          <el-form ref="ruleForm" :model="newsInfo" :rules="rules" label-width="120px" label-position="right">
            <el-form-item prop="title" label="标题：">
              <el-input v-model="newsInfo.title" size="small" placeholder="请输入…" maxlength="30"
                        show-word-limit></el-input>
            </el-form-item>
            <el-form-item prop="description" label="摘要：">
              <el-input type="textarea" v-model="newsInfo.description" size="small" placeholder="请输入…" maxlength="255"
                        show-word-limit></el-input>
            </el-form-item>
            <el-form-item prop="category" label="分类：">
              <ai-select
                  v-model="newsInfo.category"
                  placeholder="选择新闻分类"
                  :selectList="$dict.getDict('appNewsCategory')">
              </ai-select>
            </el-form-item>
            <el-form-item prop="videoUrl" label="视频：">
              <el-upload :show-file-list="false" ref="upload1"
                         action :http-request="submitUpload" :accept="accept" :limit="1">
                <div class="video" v-if="!newsInfo.videoUrl.length">
                  <div class="icon">
                    <ai-icon type="svg" icon="iconVideo"/>
                    <span>上传视频</span>
                  </div>
                  <span class="tips">支持mp4格式，单个文件最大100MB</span>
                </div>
              </el-upload>
              <video class="video-com" style="width:100%; height:100%; object-fit: fill;" muted
                     :src="newsInfo.videoUrl" controls="controls" v-if="newsInfo.videoUrl"></video>
              <el-upload :show-file-list="false" ref="upload2" action :http-request="submitUpload" :accept="accept"
                         :limit="1" v-if="newsInfo.videoUrl">
                <el-button style="margin-top: 10px;">重新选择</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item prop="thumbUrl" label="封面：">
              <ai-uploader :instance="instance" v-model="newsInfo.thumbUrl" :limit="1"
                           @change="$refs['ruleForm'].clearValidate('thumbUrl')" :cropOps="cropOps" is-crop>
                <template slot="tips">图片比例：1.8：1</template>
              </ai-uploader>
            </el-form-item>
          </el-form>
        </template>
      </ai-card>
    </template>
    <template slot="footer">
      <el-button class="footer_btn" @click="$emit('goBack')">取消</el-button>
      <el-button type="primary" class="footer_btn" @click="handleSubmit('0')">保存</el-button>
    </template>
  </ai-detail>
</template>

<script>

export default {
  name: "addVideo",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    areaId: String,
    detail: Object,
  },
  data() {
    return {
      newsInfo: {
        areaId: '',
        title: "",
        description: "",
        category: '',
        videoUrl: '',
        thumbUrl: ''
      },
      accept: ".mp4",
      rules: {
        title: {required: true, message: '请输入标题', trigger: 'blur'},
        description: {required: true, message: '请输入摘要', trigger: 'blur'},
        category: {required: true, message: '请选择分类', trigger: 'change'},
        videoUrl: {required: true, message: '请上传视频', trigger: 'blur'},
        thumbUrl: {required: true, message: '请上传封面', trigger: 'blur'},
      },
      cropOps: {
        width: "320px",
        height: "180px"
      },
    }
  },
  computed: {
    isEdit() {
      return !!this.$route.query.id;
    }
  },
  methods: {
    handleSubmit(status) {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          this.addOrUpdate(status);
        }
      })
    },

    /**
     * 上传视频
     */
    submitUpload(file) {
      this.$refs['upload1']?.clearFiles();
      this.$refs['upload2']?.clearFiles();
      this.$refs['ruleForm']?.clearValidate('videoUrl');
      const fileType = file.file.name.split(".")[1];
      const size = file.file.size / 1024 / 1024 > 100;

      if (size) {
        return this.$message.error("视频大小不能超过100M");
      }

      if (fileType && this.accept.indexOf(fileType.toLocaleLowerCase()) > -1) {
        let formData = new FormData()
        formData.append('file', file.file);
        this.instance.post(`/admin/file/add-unlimited`, formData).then(res => {
          if (res && res.data) {
            let videoList = res.data[0].split(";");
            this.newsInfo.videoUrl = videoList[0]
          }
        })
      } else {
        return this.$message.error("视频格式错误");
      }
    },
    addOrUpdate(status) {
      if (Array.isArray(this.newsInfo.thumbUrl)) {
        this.newsInfo.thumbUrl = this.newsInfo.thumbUrl[0].url
      }
      const msg = +status ? '发布成功' : this.isEdit ? '编辑成功' : '保存成功';
      this.instance.post(`/app/appnews/addOrUpdate`, {
        ...this.newsInfo,
        title: this.newsInfo.title,
        description: this.newsInfo.description,
        videoUrl: this.newsInfo.videoUrl,
        thumbUrl: this.newsInfo.thumbUrl,
        category: this.newsInfo.category,
        type: 1,
        id: this.newsInfo.id,
        status: this.newsInfo.status
      }).then(res => {
        if (res.code == 0) {
          this.$message.success(msg);
          this.$emit("goBack");
        }
      })
    },
    getDetail() {
      let {id} = this.$route.query
      this.instance.post(`/app/appnews/getById`, null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          this.newsInfo = res.data
          this.newsInfo.areaId = res.data.areaId
          this.newsInfo.id = res.data.id
          this.newsInfo.title = res.data.title;
          this.newsInfo.description = res.data.description;
          this.newsInfo.category = res.data.category
          this.newsInfo.videoUrl = res.data.videoUrl;
          this.newsInfo.thumbUrl = [{url: res.data.thumbUrl}];
        }
      })
    }
  },
  created() {
    if (this.isEdit) {
      this.getDetail();
    }
  }
}
</script>

<style lang="scss" scoped>
.add-video {
  height: 100%;
  overflow: auto;

  .video {
    width: 640px;
    height: 360px;
    border-radius: 4px;
    border: 1px dashed #D0D4DC;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .icon {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      span:nth-child(2) {
        display: inline-block;
        font-size: 16px;
        color: #333333;
        line-height: 30px;
      }

      .iconfont {
        display: inline-block;
        font-size: 40px;
        color: #2266FF;
      }
    }

    .tips {
      display: inline-block;
      font-size: 12px;
      color: #999999;
      line-height: 26px;
    }
  }

  .video-com {
    width: 640px;
    height: 360px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 2px;
    border: 1px solid #D0D4DC;
    margin-top: -40px;
  }

  ::v-deep .AiIcon {
    width: 38px;
    height: 38px;
  }

  .footer_btn {
    width: 106px;
  }
}

</style>
