<template>
  <div class="m-container">
    <h2>
      <el-page-header
        @back="onCancel"
        :content="(pageType == 'create' ? '添加' : '修改') + typeChange(type)"
      ></el-page-header>
    </h2>

    <div class="m-core">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px" style="width: 100%">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="form.title"></el-input>
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model.trim="form.order"></el-input>
        </el-form-item>
          <el-form-item label="适用范围" prop="tenantId">
          <el-select v-model="form.tenantId">
            <el-option label="对内" value="1"></el-option>
             <el-option label="对外" value="2"></el-option>
          </el-select>
        </el-form-item>
        <!-- banner图 && app按钮管理，才需要添加版本号 -->
        <el-form-item label="版本号" v-if="type == 3 || type == 6">
          <el-input v-model="form.memo"></el-input>
        </el-form-item>
        <!--  -->
        <el-form-item v-if="type == 3 || type == 6" label="链接地址">
          <el-input v-model.trim="form.linkUrl"></el-input>
        </el-form-item>
        <el-form-item v-else label="链接地址" prop="linkUrl">
          <el-input v-model.trim="form.linkUrl"></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            class="avatar-uploader"
            action="/api-web/uploadFile"
            :headers="headers"
            :show-file-list="false"
            accept=".jpg, .jpeg, .png"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="imageSize" v-if="imageSize">上传图片尺寸为：{{ imageSize }}</p>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- bidirectional data binding（双向数据绑定） -->
          <quill-editor
            class="ql-editor"
            v-model="form.content"
            ref="myQuillEditor"
            :options="editorOption"
            @change="onEditorChange($event)"
          ></quill-editor>

          <el-upload
            class="ivu-upload"
            :show-upload-list="false"
            :headers="headers"
            :on-success="handleSuccess"
            accept=".jpg, .jpeg, .png"
            :max-size="2048"
            multiple
            action="/api-web/uploadFile"
          >
            <Button icon="ios-cloud-upload-outline"></Button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="onSubmit('form')"
            type="primary"
          >立即{{ pageType == "create" ? '创建' : '修改' }}</el-button>
          <el-button @click="onReSet('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog title="插入视屏" width="500px" :visible.sync="dialogFormVisible">
      <el-form :model="dialogForm" ref="diologForm" :rules="dialogFormRules">
        <el-form-item label="封面图" label-width="90px" prop="poster">
          <el-input v-model="dialogForm.poster" style="width: 100%;" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="视屏地址" label-width="90px" prop="url">
          <el-input v-model="dialogForm.url" style="width: 100%;" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onVideoComfirm('diologForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { newsQueryId, newsAdd, newsUpdate } from "@/api/contentManager";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { vaildStudentUrl } from "@/utils/validate";
// import E from 'wangeditor'
// require styles
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import Quill from "quill";
import { quillEditor } from "vue-quill-editor";
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["image", "video"] // 链接、图片、视频
  // ["link", "image", "video"] // 链接、图片、视频
];
// 标题
const titleConfig = {
  "ql-bold": "加粗",
  "ql-color": "颜色",
  "ql-font": "字体",
  "ql-code": "插入代码",
  "ql-italic": "斜体",
  // 'ql-link': '添加链接',
  "ql-background": "背景颜色",
  "ql-size": "字体大小",
  "ql-strike": "删除线",
  "ql-script": "上标/下标",
  "ql-underline": "下划线",
  "ql-blockquote": "引用",
  "ql-header": "标题",
  "ql-indent": "缩进",
  "ql-list": "列表",
  "ql-align": "文本对齐",
  "ql-direction": "文本方向",
  "ql-code-block": "代码块",
  "ql-formula": "公式",
  "ql-image": "图片",
  "ql-video": "视频",
  "ql-clean": "清除字体样式",
  "ql-upload": "文件"
};

// 这里引入修改过的video模块并注册
import Video from "../quill/video.js";
Quill.register(Video, true);
export default {
  name: "contentOperation",
  components: {
    quillEditor
  },
  data() {
    let that = this;
    return {
      categoryList: [],
      type: this.$route.query.type,
      pageType: this.$route.query.pageType,
      organId: null,
      headers: {
        Authorization: getToken()
      },
      content: null,
      dialogFormVisible: false,
      editorIndex: 0, // 光标位置
      editorOption: {
        placeholder: "请输入内容",
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                if (value) {
                  // 调用iview图片上传
                  document.querySelector(".ivu-upload .el-upload").click();
                } else {
                  this.quill.format("image", false);
                }
              },
              video: function(value) {
                if (value) {
                  that.dialogFormVisible = true;
                  let editor = that.$refs.myQuillEditor.quill;
                  // 光标所在位置
                  that.editorIndex = editor.getSelection().index;
                } else {
                  this.quill.format("image", false);
                }
              }
            }
          }
        }
      },
      dialogForm: {
        poster: null,
        url: null
      },
      dialogFormRules: {
        poster: [
          { required: true, message: "请输入封面地址", trigger: "blur" }
        ],
        url: [{ required: true, message: "请输入视屏地址", trigger: "blur" }]
      },
      form: {
        title: null,
        order: null,
        coverImage: null,
        linkUrl: vaildStudentUrl() + "/#/specialdetail",
        type: this.$route.query.type,
        status: 1,
        content: null,
        tenantId:null,
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" }
        ],
        linkUrl: [
          { required: true, message: "请输入连接地址", trigger: "blur" }
        ],
        coverImage: [
          { required: true, message: "请选择封面图", trigger: "blur" }
        ],
        content: [{ required: true, message: "请编辑内容", trigger: "blur" }],
        tenantId: [{ required: true, message: "请选择适用范围", trigger: "blur" }]
      },
      imageSize: null
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  activated() {
    if (this.$route.query.pageType == "create") {
      this.form = {
        title: null,
        order: null,
        coverImage: null,
        linkUrl: vaildStudentUrl() + "/#/specialdetail",
        type: this.$route.query.type,
        status: 1,
        content: null,
        tenantId:null
      };
      this.$refs["form"].resetFields();
    }
    this.type = this.$route.query.type;
    this.pageType = this.$route.query.pageType;
    this.init();
  },
  methods: {
    init() {
      this.getList();
      this.addQuillTitle();

      // this.form.type
      let tempTitle = {
        1: "468px * 552px",
        2: "456px * 288px",
        3: "686px * 140px",
        4: null
      };
      this.imageSize = tempTitle[this.form.type];
    },
    onVideoComfirm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let dialogForm = this.dialogForm;
          // 获取富文本组件实例
          let quill = this.editor;
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(this.editorIndex, "video", dialogForm);
          // 调整光标到最后
          quill.setSelection(this.editorIndex + 1);

          this.dialogFormVisible = false;
          this.dialogForm = {
            poster: null,
            url: null
          };
        } else {
          return false;
        }
      });
    },
    addQuillTitle() {
      const oToolBar = document.querySelector(".ql-toolbar"),
        aButton = oToolBar.querySelectorAll("button"),
        aSelect = oToolBar.querySelectorAll("select");
      aButton.forEach(function(item) {
        if (item.className === "ql-script") {
          item.value === "sub" ? (item.title = "下标") : (item.title = "上标");
        } else if (item.className === "ql-indent") {
          item.value === "+1"
            ? (item.title = "向右缩进")
            : (item.title = "向左缩进");
        } else {
          item.title = titleConfig[item.classList[0]];
        }
      });
      aSelect.forEach(function(item) {
        item.parentNode.title = titleConfig[item.classList[0]];
      });
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.pageType == "create") {
            if (this.form.id) {
              // 判断有没有Id，如果有则删除
              delete this.form.id;
            }
            // return false
            newsAdd(this.form).then(res => {
              this.messageTips("添加", res);
            });
          } else if (this.pageType == "update") {
            newsUpdate(this.form).then(res => {
              this.messageTips("修改", res);
            });
          }
        } else {
          return false;
        }
      });
    },
    messageTips(title, res) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.$router.push({
          path: "/contentManager/contentManager",
          query: {
            type: this.typeIndex(this.type)
          }
        });
      } else {
        this.$message.error(res.msg);
      }
    },
    onCancel() {
      this.$router.push({
        path: "/contentManager/contentManager",
        query: {
          type: this.typeIndex(this.type)
        }
      });
    },
    handleSuccess(res) {
      // 获取富文本组件实例
      let quill = this.editor;
      // 如果上传成功
      if (res.code) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.data.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        this.$message.error("图片插入失败");
      }
    },
    onReSet(formName) {
      this.$refs[formName].resetFields();
    },
    getList() {
      if (this.pageType == "create") {
        return;
      } else {
        newsQueryId({ id: this.$route.query.id }).then(res => {
          if (res.code == 200) {
            let result = res.data;
            let form = this.form;
            this.form = {
              id: result.id,
              title: result.title,
              order: result.order,
              coverImage: result.coverImage,
              linkUrl: result.linkUrl,
              type: result.type,
              status: result.status,
              memo: result.memo,
              content: result.content,
              tenantId:result.tenantId.toString()
            };
          }
        });
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.coverImage = res.data.url;
    },
    beforeAvatarUpload(file) {
      const imageType = {
        "image/png": true,
        "image/jpeg": true
      };
      const isImage = imageType[file.type];
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isImage && isLt2M;
    },
    typeChange(type) {
      let tempTitle = {
        1: "精彩活动",
        2: "热门资讯",
        4: "专项训练",
        5: "闪页管理",
        3: "BANNER管理",
        6: "APP按钮管理"
      };
      return tempTitle[type];
    },
    typeIndex(type) {
      let tempTitle = {
        1: 0,
        2: 1,
        3: 4,
        4: 2,
        5: 3,
        6: 5
      };
      return tempTitle[type];
    },
    onEditorChange({ quill, html, text }) {
      this.form.content = html;
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    }
  }
};
</script>
<style lang="scss" scoped>
.m-container {
  min-width: 100%;
}
.el-input {
  width: 400px;
}
/deep/.ql-editor {
  min-height: 300px;
}
.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
.el-row {
  margin-top: 40px;
}
.el-col {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: flex-end;
  margin-right: 50%;
}
.el-input-group {
  width: 200px;
  margin: 0 20px;
}
/deep/.el-tree-node__content {
  height: 40px !important;
}
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.ivu-upload {
  display: none;
}
</style>