<template>
  <div class="storeChangePower">
    <el-tag>新增文章</el-tag>
    <div class="KS">
      <el-form
        label-width="120px"
        :model="newsForm"
        size="mini"
        label-position="left"
        :rules="newsFormRules"
        ref="newsForm"
      >
        <el-form-item label="文章名称" prop="name">
          <el-input class="name" v-model="newsForm.name"></el-input>
        </el-form-item>
        <el-form-item label="选择分类" prop="type">
          <el-select
            v-model="newsForm.type"
            placeholder="请选择"
            @change="choose"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择标签" prop="label">
          <el-select
            v-model="newsForm.label"
            multiple
            filterable
            @change="choose"
            size="small"
            placeholder="请选择文章标签"
          >
            <el-option
              v-for="item in labelList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文章封面" prop="pic">
          <div>(尺寸300*150)</div>
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :on-success="uploadimg"
            :show-file-list="false"
            :limit="1"
            name="image"
          >
            <img v-if="newsForm.pic" :src="newsForm.pic" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章排序" prop="rank">
          <el-input class="name" v-model="newsForm.rank"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="newsForm.isshow"
            active-text="是"
            inactive-text="否"
          ></el-switch>
        </el-form-item>
        <!-- 上传视频按钮 -->
        <el-form-item label="视频上传">
          <div class="uploadVideo">
            <el-button type="primary" size="mini">
              点击上传
              <form id="videoform">
                <input
                  type="file"
                  ref="inputvideo"
                  accept="video/mp4"
                  @change="addVideo"
                  name="file"
                  id="file"
                />
              </form>
            </el-button>
            <!-- 进度条 -->
            <el-progress
              :text-inside="true"
              :stroke-width="15"
              :percentage="percentage"
            ></el-progress>
            <el-button
              v-if="playerOptions.sources[0].src != ''"
              @click="cancelVideo"
              type="info"
              size="mini"
              >取消上传</el-button
            >
          </div>
        </el-form-item>
        <!-- 上传视频播放插件 -->
        <div v-if="playerOptions.sources[0].src != ''">
          <video-player
            class="video-player vjs-custom-skin"
            ref="videoPlayer"
            :playsinline="true"
            :options="playerOptions"
          ></video-player>
        </div>
      </el-form>
      <div class="editor-box">
        <el-upload
          v-show="false"
          class="avatar-uploader"
          :action="uploadUrl"
          name="image"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"
          id="quill-upload"
        >
        </el-upload>
        <quill-editor
          class="editor"
          v-model="newsForm.content"
          :options="editorOption"
          @change="onEditorChange($event)"
          @ready="onEditorReady($event)"
          ref="myQuillEditor"
        ></quill-editor>
      </div>
      <div class="next">
        <el-button type="primary" @click="confrim('newsForm')" size="mini"
          >确认编辑</el-button
        >
      </div>
      <div id="progress">
        <div id="finish" style="width: 0%;" progress="0"></div>
      </div>
    </div>
  </div>
</template>

<script>
var xhr = new XMLHttpRequest();
var form_data = new FormData();
const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],
    
    [{'header': 1}, {'header': 2}], // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}], // superscript/subscript
    [{'indent': '-1'}, {'indent': '+1'}], // outdent/indent
    [{'direction': 'rtl'}], // text direction
    
    [{'size': ['10px', '12px', '14px', '16px' ,'18px', '20px', '22px', '24px', '26px', '32px', '48px']}], // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],
    
    [{'color': []}, {'background': []}], // dropdown with defaults from theme
    [{'font': []}],
    [{'align': []}],
    ['link', 'image'],
    ['clean'] // remove formatting button
]
import upload from "../components/webupload";
export default {
  data() {
    return {
      searchHc: "",
      uploadUrl: "",
      newsForm: {
        isshow: true,
        pic: ""
      },
      typeList: [],
      labelList: [],
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function(value) {
                if (value) {
                  document.querySelector("#quill-upload input").click();
                } else {
                  this.quill.format("image", false);
                }
              }
            }
          }
        }
      },
      content: "",
      newsFormRules: {
        name: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        type: [{ required: true, message: "请输入文章分类", trigger: "blur" }],
        label: [{ required: true, message: "请输入文章标签", trigger: "blur" }],
        rank: [
          {
            pattern: /^100$|^(\d|[1-9]\d)$/,
            message: "输入的值需大于0且不能为小数",
            trigger: "blur"
          }
        ],
        pic: [{ required: true, message: "请上传文章封面", trigger: "blur" }]
      },

      // 视频
      blob_num: 1,
      total_blob_num: "",
      file_name: "",
      file: "",
      LENGTH: 1048576,
      blob: {},
      start: 0,
      end: 0,
      total_size: 0,
      playerOptions: {
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频(如果浏览器支持)
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式,并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字(例如"16:9"或"4:3")
        fluid: true, // 当true时,Video.js player将拥有流体大小。换句话说,它将按比例缩放以适应其容器。
        sources: [
          {
            type: "", //这里的种类支持很多种:基本视频格式、直播、流媒体等,具体可以参看git网址项目
            src: "" //url地址
          }
        ],
        notSupportedMessage: "此视频暂无法播放,请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true //全屏按钮
        }
      },
      percentage: 0, // 进度条
      quillUpdateImg: false,
    };
  },
  components: {
    upload
  },
  mounted() {
    this.getNewsInfo();
    this.uploadUrl = this.$global.baseUrl + "index/Uploader/upload";
  },
  methods: {
    getNewsInfo() {
      this.$get("Index/news/newsinfo", {}).then(res => {
        console.log(res);
        if (res.data.status) {
          this.typeList = res.data.type;
          this.labelList = res.data.label;
        }
      });
    },
    addNews(data) {
      this.$post("Index/news/newsinfo", data).then(res => {
        console.log(res);
      });
    },
    choose(e) {
      console.log(e);
    },
    confrim(newsForm) {
      this.$refs[newsForm].validate(valid => {
        if (valid) {
          if (this.newsForm.content) {
            this.newsForm.label = this.newsForm.label.join(","); // 标签转换
            if (this.newsForm.isshow) {
              this.newsForm.isshow = 1;
            } else {
              this.newsForm.isshow = 0;
            }
            console.log(this.newsForm);
            this.postNews();
          } else {
            this.$alert("请输入文章内容", "注意", {
              confirmButtonText: "确定"
            });
          }
        } else {
          return false;
        }
      });
    },
    // 提交文章
    postNews() {
      this.$post("Index/news/newsinfo", this.newsForm).then(res => {
        console.log(res);
        if (res.data.status) {
          this.$router.push({ path: "/news/newsList" });
        }
      });
    },
    // 上传视频
    addVideo(e) {
      console.log(e);
      this.file = document.getElementById("file").files[0];
      this.total_blob_num = Math.ceil(this.file.size / this.LENGTH);
      console.log(this.total_blob_num);
      if (file) {
        this.blob = this.cutFile(this.file);
        this.videoPost();
      }
    },
    //  切割视频
    cutFile(file) {
      this.start = this.end;
      this.end = this.start + this.LENGTH;
      var file_blob = file.slice(this.start, this.end);
      return file_blob;
    },
    // 上传视频接口(xhr)
    videoPost() {
      var that = this;
      form_data.append("file", this.blob);
      form_data.append("blob_num", this.blob_num);
      form_data.append("total_blob_num", this.total_blob_num);
      form_data.append("file_name", this.file.name);
      xhr.open(
        "POST",
        "http://hospital.wxsshop.com/Index/Uploader/videoupload",
        false
      );
      xhr.onreadystatechange = function() {
        console.log(that.blob_num, that.total_blob_num);
        if (that.total_blob_num == 1) {
          that.percentage = 100;
        } else {
          that.percentage = Number(
            Math.min(100, parseInt((that.blob_num / that.total_blob_num) * 100))
          );
        }
        var t = setTimeout(function() {
          if (that.blob_num < that.total_blob_num) {
            that.blob = that.cutFile(that.file);
            that.blob_num += 1;
            that.videoPost();
          } else {
            setTimeout(t);
          }
        }, 1000);
      };
      xhr.send(form_data);
      if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
        // console.log(xhr.responseText);
        let responseText = JSON.parse(xhr.responseText);
        console.log(responseText);
        if (responseText.code == 2) {
          that.newsForm.videourl = responseText.file_path;
          that.playerOptions.sources[0].src = that.newsForm.videourl;
          console.log(that.playerOptions);
        }
        // that.$refs.inputvideo.value =null
      } else {
        console.log("request was unsuccessful:" + xhr.status);
      }
    },
    // 取消视频
    cancelVideo() {
      this.$router.go(0);
    },
    // 上传封面
    uploadimg(res, file) {
      console.log(res.status);
      if (res.status) {
        this.newsForm.pic = res.url;
      }
    },
    beforeUpload(res, file) {
            this.quillUpdateImg = true
        },
        // 上传图片成功
        uploadSuccess(res, file) {
            // res为图片服务器返回的数据
            // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill
            // 如果上传成功
            console.log(res)
            if (res.status == 1) {
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片 res.info为服务器返回的图片地址
                quill.insertEmbed(length, 'image', res.url)
                // 调整光标到最后
                quill.setSelection(length + 1)
            } else {
                this.$message.error('图片插入失败')
            }
            // loading动画消失
            this.quillUpdateImg = false
        },
        // 上传图片失败
        uploadError(res, file) {
            // loading动画消失
            this.quillUpdateImg = false
            this.$message.error('图片插入失败')
        },
        onEditorChange(){},
        onEditorReady(){},
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.storeChangePower {
  padding: 20px;
  box-sizing: border-box;
}
.KS {
  box-sizing: border-box;
  padding: 10px;
  border-radius: 10px;
  margin-top: 10px;
  font-size: 12px;
}
.name {
  width: 300px;
}
.KS-header {
  display: flex;
  align-items: center;
  margin: 10px 0px;
}
.search-input {
  width: 150px;
  margin: 0px 10px;
}
.el-divider--horizontal {
  margin: 12px 0px;
}
/* 按钮 */
.ks-btn {
  width: 80%;
  margin: 0 auto;
}
.ks-btn-list {
  display: flex;
  flex-wrap: wrap;
}
.ke-btn-item {
  width: 20%;
  height: 30px;
  line-height: 30px;
  border-radius: 20px;
  background-color: #9f6cd9;
  margin: 10px;
  text-align: center;
  color: #ffffff;
  cursor: pointer;
}
/* 已授权 */
.Power {
  background-color: #9f6cd9;
}
.NOpower {
  background-color: #a3a0a5;
}
.ke-btn-YJ {
  width: 100px;
  height: 30px;
  line-height: 30px;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  cursor: pointer;
  color: #fff;
}
.allPower {
  background-color: #4f1487;
}
.allCancel {
  background-color: #a3a0a5;
}
.link-box {
  display: flex;
  box-sizing: border-box;

  justify-content: space-between;
  align-items: center;
  padding: 5px 0px 5px 10px;
  background-color: #f7f7f7;
}
.num {
  width: 100px;
}
.next {
  width: 80%;
  margin-top: 150px;
  display: flex;
  justify-content: center;
}
/* 富文本编辑框 */
.editor-box {
  width: 80%;
  height: 200px;
}
.editor {
  width: 100%;
  height: 100%;
}
/* 视频 */
.video-player {
  width: 50%;
  display: block;
  margin-bottom: 20px;
}
.uploadVideo {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.el-progress {
  width: 35%;
  margin: 0px 20px;
}
.uploadVideo input {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  opacity: 0;
}
/* 标签 */
.el-tag.el-tag--info {
  background-color: #f4f4f5 !important;
  border-color: #9f6cd9 !important;
  color: #fff !important;
}
/* 上传封面图 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  width: 185px;
  height: 185px;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar-uploader:hover {
  border-color: #9f6cd9;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #9f6cd9;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

houqq
245 声望14 粉丝