<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="policyType" label="类型：">
              <ai-select
                  v-model="newsInfo.policyType"
                  placeholder="选择新闻类型"
                  :selectList="$dict.getDict('newsCenterPolicyType')">
              </ai-select>
            </el-form-item>
            <el-form-item label="发布地区：" prop="areaId">
              <ai-area-get v-model="newsInfo.areaId" :instance="instance" :root="areaId"/>
            </el-form-item>
            <el-form-item prop="videoFile" label="视频：">
              <el-upload :show-file-list="false" ref="upload1"
                         action :http-request="submitUpload" :accept="accept" :limit="1">
                <div class="video" v-if="!newsInfo.videoFile.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.videoFile[0].url" controls="controls" v-if="newsInfo.videoFile.length"></video>
              <el-upload :show-file-list="false" ref="upload2" action :http-request="submitUpload" :accept="accept"
                         :limit="1" v-if="newsInfo.videoFile.length">
                <el-button style="margin-top: 10px;">重新选择</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item prop="coverFile" label="封面：">
              <ai-uploader :instance="instance" v-model="newsInfo.coverFile" :limit="1"
                           @change="$refs['ruleForm'].clearValidate('coverFile')" :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('1')" v-if="!isEdit">发布</el-button>
      <el-button class="footer_btn" @click="handleSubmit('0')">保存</el-button>
    </template>
  </ai-detail>
</template>

<script>
import mp4box from 'mp4box'

export default {
  name: "addVideo",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    areaId: String,
    detail: Object,
  },
  data() {
    return {
      newsInfo: {
        areaId: '',
        title: "",
        policyType: '',
        videoFile: [],
        coverFile: []
      },
      accept: ".mp4",
      rules: {
        title: {required: true, message: '请输入标题', trigger: 'blur'},
        areaId: {required: true, message: '请选择 发布地区', trigger: 'blur'},
        policyType: {required: true, message: '请选择类型', trigger: 'change'},
        videoFile: {required: true, message: '请上传视频', trigger: 'blur'},
        coverFile: {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('videoFile');
      const fileType = file.file.name.split(".")[1];
      const size = file.file.size / 1024 / 1024 > 100;
      let mp4boxfile = mp4box.createFile();
      const reader = new FileReader();
      reader.readAsArrayBuffer(file.file);
      reader.onload = (e) => {
        const arrayBuffer = e.target.result;
        arrayBuffer.fileStart = 0;
        mp4boxfile.appendBuffer(arrayBuffer);
      };
      mp4boxfile.onReady = (info) => {
        let codec = info.mime.match(/codecs="(\S*),/)[1]
        if (codec.indexOf('avc') === -1) {
          return this.$message.error("视频编码格式不支持")
        }

        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.videoFile.splice(0, 1, {
                id: videoList[1],
                url: videoList[0]
              })
            }
          })
        } else {
          return this.$message.error("视频格式错误");
        }

      };
    },
    addOrUpdate(status) {
      const msg = +status ? '发布成功' : this.isEdit ? '编辑成功' : '保存成功';
      this.instance.post(`/app/appnewscenterinfo/addOrUpdate`, {
        title: this.newsInfo.title,
        videoFile: {
          id: this.newsInfo.videoFile[0].id
        },
        coverFile: {
          id: this.newsInfo.coverFile[0].id
        },
        policyType: this.newsInfo.policyType,
        areaId: this.areaId,
        type: 1,
        id: this.detail.id,
        status: this.isEdit ? this.detail.status : status
      }).then(res => {
        if (res.code == 0) {
          this.$message.success(msg);
          this.$emit("goBack");
        }
      })
    },
    getDetail() {
      let {id} = this.$route.query
      this.instance.post(`/app/appnewscenterinfo/queryDetailById`, null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          this.newsInfo.areaId = res.data.areaId
          this.newsInfo.title = res.data.title;
          this.newsInfo.policyType = res.data.policyType
          this.newsInfo.videoFile = [{...res.data.videoFile, url: res.data.videoFile.accessUrl}];
          this.newsInfo.coverFile = [{...res.data.coverFile, url: res.data.coverFile.accessUrl}];
        }
      })
    }
  },
  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>
