<template>
  <div class="container add-edit-video">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      center
      width="568px"
      title="添加视频"
      :visible.sync="addEditdialogVisib"
      customClass="add-edit-video-dlg"
      :before-close="cancelHandle"
    >
      <div>
        <el-form :model="addEditVideo" :rules="rules" ref="ruleFormVideo" class="demo-ruleForm">
          <el-form-item prop="audioName">
            <div style="display: flex; justify-content: space-between">
              <el-input style="width: 75%" clearable placeholder="请上传视频" v-model="addEditVideo.videoName"></el-input>
              <el-upload action="" accept=".mp4" :http-request="handleUpload" :before-upload="handelBeforeUploadVideo" :show-file-list="false" :disabled="startUpload">
                <el-button type="primary" :loading="startUpload">上传视频</el-button>
              </el-upload>
              <el-progress type="circle" :percentage="percentage" width="40" style="margin-left: 10px" v-if="startUpload"></el-progress>
            </div>
            <p style="color: #ff3737">注：视频格式支持mp4</p>
          </el-form-item>
          <el-form-item prop="industryId">
            <el-select style="width: 100%" placeholder="请选择行业" v-model="addEditVideo.industryId" clearable @change="selectChangeHandle">
              <el-option 
              v-for="item in chartPermissionList.filter(item => item.PermissionName != '宏观' && item.PermissionName != '策略' && item.PermissionName != '研选订阅')" 
                :label="item.PermissionName" :key="item.ChartPermissionId" :value="item.ChartPermissionId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="property">
            <!-- <el-cascader
              style="width: 100%"
              @focus="industrySelectFocus"
              placeholder="请选择产业"
              v-model="addEditVideo.property"
              :props="{ ...defaultProps }"
              :options="selectedIndustryArr"
              :key="addEditVideo.industryId"
              filterable
              clearable
            ></el-cascader> -->
            <el-select v-model="addEditVideo.property" placeholder="请选择产业" clearable filterable
            style="width: 100%;" @focus="industrySelectFocus">
              <el-option :label="item.PermissionName" :value="item.ChartPermissionId" 
              v-for="item in selectedIndustryArr" :key="item.ChartPermissionId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="publishDate">
            <el-date-picker
              style="width: 100%"
              v-model="addEditVideo.publishDate"
              type="date"
              placeholder="请选择发布时间"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              @change="conditionChange"
            >
            </el-date-picker>
          </el-form-item>
          <div class="uploadImageContain">
            <el-form-item prop="imgUrl">
              <div class="imgUploadBox">
                <el-upload action="" :http-request="(e)=>handleImageUpload(e,'imgUrl')"
                :multiple="false" :show-file-list="false" v-if="!addEditVideo.imgUrl">
                  <div class="image-upload-item">
                    <img src="~@/assets/icons/uploadImg-blue.svg"/>
                    <span>添加列表页封面</span>
                  </div>
                </el-upload>
                <div v-else class="uploaded-image-item">
                  <el-image :src="addEditVideo.imgUrl" 
                  class="videoImage"
                  :preview-src-list="[addEditVideo.imgUrl]"/>
                  <span class="del-image" @click="addEditVideo.imgUrl=''">删除</span>
                </div>   
              </div>
            </el-form-item>
          
            <el-form-item prop="detailImgUrl">
              <div class="imgUploadBox">
                <el-upload action="" :http-request="(e)=>handleImageUpload(e,'detailImgUrl')"
                :multiple="false" :show-file-list="false" v-if="!addEditVideo.detailImgUrl" >
                <div class="image-upload-item">
                    <img src="~@/assets/icons/uploadImg-blue.svg"/>
                    <span>添加详情页封面</span>
                  </div>
                </el-upload>
                <div v-else class="uploaded-image-item">
                  <el-image :src="addEditVideo.detailImgUrl" 
                  class="videoImage"
                  :preview-src-list="[addEditVideo.detailImgUrl]"/>
                  <span class="del-image" @click="addEditVideo.detailImgUrl=''">删除</span>
                </div>            
              </div>
            </el-form-item>
            <el-form-item prop="shareImgUrl">
              <div class="imgUploadBox">
                <el-upload action="" :http-request="(e)=>handleImageUpload(e,'shareImgUrl')"
                :multiple="false" :show-file-list="false" v-if="!addEditVideo.shareImgUrl" >
                <div class="image-upload-item">
                    <img src="~@/assets/icons/uploadImg-blue.svg"/>
                    <span>添加视频分享图</span>
                  </div>
                </el-upload>
                <div v-else class="uploaded-image-item">
                  <el-image :src="addEditVideo.shareImgUrl" 
                  class="videoImage"
                  :preview-src-list="[addEditVideo.shareImgUrl]"/>
                  <span class="del-image" @click="addEditVideo.shareImgUrl=''">删除</span>
                </div>            
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSubmit(0)">保存</el-button>
        <el-button type="primary" v-if="publishStatus != 1" @click="confirmSubmit(1)">发布</el-button>
        <el-button @click="cancelHandle">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOSSSign } from "@/api/api.js";
import MD5 from "js-md5";
import { raiInterface, raiVideoApi } from "@/api/api.js";
export default {
  name: "",
  components: {},
  props: {
    addEditdialogVisib: {
      type: Boolean,
      default: false,
    },
    chartPermissionList: {
      type: Array,
      default: [],
    },
    playDetailsList: {
      default: {},
      type: Object,
    },
  },
  data() {
    return {
      addEditVideo: {
        videoName: "", //音频名称
        industryId: "", //行业id
        property: "", //产业名称
        publishDate: "", //发布时间
        videoUrl: "", //视频链接
        VideoSeconds: "", //时长
        imgUrl:"", // 视频封面
        shareImgUrl:"", // 分享的视频封面
        detailImgUrl:""// 详情的视频封面
      },
      rules: {
        videoName: [{ required: true, message: "请上传视频", trigger: "blur" }],
        industryId: [{ required: true, message: "请选择行业", trigger: "change" }],
        property: { required: true, message: "请选择产业", trigger: "change" },
        publishDate: [{ required: true, message: "请选择发布时间", trigger: "change" }],
        imgUrl:{ required: true, message: "请选择列表页封面", trigger: "change" },
        shareImgUrl:{ required: true, message: "请选择视频分享图", trigger: "change" },
        detailImgUrl:{ required: true, message: "请选择详情页封面", trigger: "change" }
      },
      videoId: 0,
      publishStatus: 0,
      industryArr: [],
      selectedIndustryArr:[],
      defaultProps: {
        label: "PermissionName",
        children: "List",
        value: "ChartPermissionId",
      },
      percentage: 0,
      startUpload: false, //开始上传
    };
  },
  computed: {},
  watch: {
    playDetailsList: {
      async handler(newval) {
        if (JSON.stringify(newval) != "{}") {
          await this.getIndustry(newval.ChartPermissionId);
          console.log(newval);
          this.addEditVideo = {
            videoName: newval.VideoName, //音频名称
            industryId: newval.ChartPermissionId, //行业id
            property: newval.IndustryId || "", //产业名称
            publishDate: newval.PublishDate, //发布时间
            videoUrl: newval.VideoUrl, //视频链接
            VideoSeconds: newval.VideoDuration, //时长
            imgUrl:newval.ImgUrl, // 视频封面
            shareImgUrl:newval.ShareImgUrl, // 分享的视频封面
            detailImgUrl:newval.DetailImgUrl
          };
          this.videoId = newval.VideoId;
          this.publishStatus = newval.PublishStatus;
        } else {
          this.videoId = 0;
          this.selectedIndustryArr=[]
          this.publishStatus = 0;
        }
      },
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    /* 获取全部的行业 前的判断 */
    industrySelectFocus() {
      if (!this.addEditVideo.industryId) {
        this.$message.error("请先选择行业");
      }
    },
    // 行业更改
    selectChangeHandle(value){
      this.addEditVideo.property=""
      value?this.getIndustry(value):this.selectedIndustryArr =[]
    },
    /* 获取选择的行业 */
    getIndustry(industryId) {
      if (this.industryArr.length){
        this.selectedIndustryArr = this.industryArr.filter(item => item.ChartPermissionId == industryId)[0].List
        return;
      } 
      raiInterface.getListIndustrial().then((res) => {
        if (res.Ret === 200) {
          this.industryArr = res.Data.List || [];
          this.selectedIndustryArr = this.industryArr.filter(item => item.ChartPermissionId == industryId)[0].List
          // if (this.addEditVideo.property) {
            // let valId = "";
            // this.industryArr.forEach((item) => {
            //   if (item.List.some((key) => key.ChartPermissionId == this.addEditVideo.property)) {
            //     valId = item.ChartPermissionId;
            //   }
            // });
          //   this.addEditVideo.property = [industryId, this.addEditVideo.property];
          // }
        }
      });
    },
    //获取视频时长的promise
    handleGetDuration(file) {
      return new Promise((resolve, reject) => {
        const fileUrl = URL.createObjectURL(file);
        const audioEl = new Audio(fileUrl);
        audioEl.addEventListener("loadedmetadata", (e) => {
          resolve(audioEl.duration);
        });
      });
    },

    //上传视频判断格式
    handelBeforeUploadVideo(e) {
      if (e.type != "video/mp4") {
        this.$message.warning("上传失败，上传视频格式不正确");
        return false;
      }
    },

    // 上传视频
    async handleUpload(e) {
      const duration = await this.handleGetDuration(e.file);
      // 取消视频的大小校验 -- 查研观向 8.4
      // if (duration > 600) {
      //   this.$message.warning("视频时长不得超过10分钟");
      //   return;
      // }
      console.log(e, duration);
      this.addEditVideo.videoName = e.file.name;
      this.addEditVideo.VideoSeconds = duration + ""; //时常
      const res = await getOSSSign();
      if (res.Ret === 200) {
        let accessKeyId = res.Data.AccessKeyId;
        let accessKeySecret = res.Data.AccessKeySecret;
        let stsToken = res.Data.SecurityToken;
        this.handleUploadToOSS(e.file, accessKeyId, accessKeySecret, stsToken);
      }
    },
    //上传到阿里云
    async handleUploadToOSS(file, accessKeyId, accessKeySecret, stsToken) {
      this.startUpload = true;
      const ALOSSINS = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
        region: "oss-cn-shanghai",
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: accessKeyId,
        accessKeySecret: accessKeySecret,
        // 从STS服务获取的安全令牌（SecurityToken）。
        stsToken: stsToken,
        // 填写Bucket名称，例如examplebucket。
        bucket: "hzchart",
        endpoint: "hzstatic.hzinsights.com",
        cname: true,
        timeout: 600000,
      });
      // 生成文件名
      const t = new Date().getTime().toString();
      const temName = `static/yb/video/${MD5(t)}.${file.name.split(".")[1]}`;
      console.log(temName);

      const options = {
        // 获取分片上传进度、断点和返回值。
        progress: (p, cpt, res) => {
          console.log(p);
          this.percentage = parseInt(p * 100);
        },
        // 设置并发上传的分片数量。
        parallel: 10,
        // 设置分片大小。默认值为1 MB，最小值为100 KB。
        partSize: 1024 * 1024 * 10, // 10MB
      };
      try {
        const res = await ALOSSINS.multipartUpload(temName, file, { ...options });
        console.log("上传结果", res);
        if (res.res.status === 200) {
          this.addEditVideo.videoUrl = "https://hzstatic.hzinsights.com/" + res.name;
          this.startUpload = false;
          this.percentage = 0;
        }
      } catch (error) {
        this.$message.warning("上传失败，请刷新重试");
        this.startUpload = false;
        this.percentage = 0;
      }
    },
    //保存或发布
    confirmSubmit(type) {
      this.$refs.ruleFormVideo.validate(async (valid) => {
        if (valid) {
          const res = await raiVideoApi.addVideo({
            VideoName: this.addEditVideo.videoName,
            ChartPermissionId: this.addEditVideo.industryId,
            IndustryId: this.addEditVideo.property || 0,
            VideoUrl: this.addEditVideo.videoUrl,
            VideoDuration: this.addEditVideo.VideoSeconds,
            PublishDate: this.addEditVideo.publishDate,
            PublishOrSave: type==1?type:this.publishStatus,
            VideoId: this.videoId,
            ImgUrl:this.addEditVideo.imgUrl,
            ShareImgUrl:this.addEditVideo.shareImgUrl,
            DetailImgUrl:this.addEditVideo.detailImgUrl
          });
          if (res.Ret === 200) {
            this.$message.success("添加成功");
            this.cancelHandle();
            this.$parent.getVideoList();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // ------------------图片上传
    handleImageUpload(e,type){
      let formData = new FormData()
      formData.append("file", e.file)
      raiInterface.upload(formData).then(res=>{
        if(type=='imgUrl'){
          this.addEditVideo.imgUrl = res.Data.ResourceUrl
        }else if(type=='shareImgUrl'){
          this.addEditVideo.shareImgUrl = res.Data.ResourceUrl
        }else{
          this.addEditVideo.detailImgUrl = res.Data.ResourceUrl
        }
        // 触发表单验证
        this.$refs.ruleFormVideo.validateField(type)
      })  
    },
    //详情进来编辑
    async editVideo() {
      const res = await raiVideoApi.editVideo({});
    },
    cancelHandle() {
      this.$refs.ruleFormVideo.resetFields();
      this.addEditVideo = {
        videoName: "", //音频名称
        industryId: "", //行业id
        property: "", //产业名称
        publishDate: "", //发布时间
        videoUrl: "", //视频链接
        VideoSeconds: "", //时长
        imgUrl:"", // 视频封面
        shareImgUrl:"", // 分享的视频封面
        detailImgUrl:""
      };
      this.$emit("update:addEditdialogVisib", false);
      this.$emit("update:playDetailsList", {});
    },
  },
};
</script>
<style lang="scss">
.add-edit-video {
  .add-edit-video-dlg {
    .el-input {
      width: 100%;
    }
  }
}
</style>
<style lang="scss" scoped>
.uploadImageContain{
  display: flex;
  justify-content: space-between;
  .imgUploadBox{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 110px;
    height: 110px;
    .image-upload-item{
      display: flex;
      flex-direction: column;
      justify-content: center;
      img{
        height: 32px;
      }
      span{
        color: #409eff;
        font-weight: 400;
        font-size: 14px;
      }
    }
    .uploaded-image-item{
      height: 110px;
      width: 110px;
      display: flex;
      justify-content: center;
      .videoImage{
        border-radius: 1px;
      }
      .del-image{
        display: none;
        color: #fff;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        text-align: center;
        line-height: 24px;
        width: 110px;
        background-color: rgba($color: #000000, $alpha: 0.8);
        cursor: pointer;
      }
      &:hover{
        .del-image{
          display: block;
        }
      }
    }
  }
}
</style>
