<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel"
                      :content="(pageType == 'create' ? '添加时间充值活动' : '查看时间充值活动')"></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="name">
          <el-input v-model.trim="form.name"
                    placeholder="请输入活动名称"
                    :disabled="pageType=='create'?false:true"></el-input>
        </el-form-item>
        <el-form-item label="适用范围"
                      prop="suitableUser">
          <el-select v-model="form.suitableUser"
                     :disabled="pageType=='create'?false:true"
                     placeholder="请选择适用范围">
            <el-option label="全部"
                       value="ALL"></el-option>
            <el-option label="新用户"
                       value="NEW"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期"
                      prop="date">
          <!-- <el-input v-model="form.memo"></el-input> -->
          <el-date-picker :disabled="pageType=='create'?false:true"
                          v-model="form.date"
                          type="datetimerange"
                          :picker-options="{
                            firstDayOfWeek:1
                          }"
                          :default-time="['00:00:00', '23:59:59']"
                          align="right"
                          unlink-panels
                          value-format="yyyy-MM-dd HH:mm:ss"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <!--  -->
        <el-form-item label="价格"
                      prop="totalPrice">
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="form.totalPrice"
                    placeholder="请输入价格"
                    :disabled="pageType=='create'?false:true"></el-input>
        </el-form-item>
        <el-form-item label="折扣价"
                      prop="discountPrice">
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="form.discountPrice"
                    placeholder="请输入折价格"
                    :disabled="pageType=='create'?false:true"></el-input>
        </el-form-item>
        <el-form-item label="购买分钟数"
                      prop="purchaseMinutes">
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="form.purchaseMinutes"
                    placeholder="请输入购买分钟"
                    :disabled="pageType=='create'?false:true"></el-input>
        </el-form-item>
        <el-form-item label="赠送分钟数"
                      prop="giveMinutes">
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="form.giveMinutes"
                    placeholder="请输入赠送分钟"
                    :disabled="pageType=='create'?false:true"></el-input>
        </el-form-item>
        <el-form-item label="活动图"
                      prop="coverImg">
          <el-upload class="avatar-uploader"
                     action="/api-web/uploadFile"
                     :disabled="pageType=='create'?false:true"
                     :headers="headers"
                     :show-file-list="false"
                     accept=".jpg, .jpeg, .png, .gif"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="form.coverImg"
                 :src="form.coverImg"
                 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="detail">
          <!-- bidirectional data binding（双向数据绑定） -->
          <quill-editor class="ql-editor"
                        :disabled="pageType=='create'?false:true"
                        v-model="form.detail"
                        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, .gif"
                     :max-size="2048"
                     multiple
                     action="/api-web/uploadFile">
            <Button icon="ios-cloud-upload-outline"></Button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="pageType == 'create'">
          <el-button @click="onSubmit('form')"
                     type="primary">立即{{ pageType == "create" ? '创建' : '修改' }}</el-button>
          <el-button @click="onReSet('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getActivitieQuery, getActivitieMerge } from "@/api/appTenant";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { vaildStudentUrl } from "@/utils/validate";
import load from '@/utils/loading'
// 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": "文件"
};
let validPrice = (rule, value, callback) => {
  if (value == '' && typeof value == 'string' || value == null) {
    callback(new Error('请输入金额'))
  } else if (value < 0) {
    callback(new Error('输入金额必须大于或等于0'))
  } else if (value >= 100000) {
    callback(new Error('输入金额必须小于100000'))
  } else {
    callback()
  }
}
let validMinutes = (rule, value, callback) => {
  if (value == '' && typeof value == 'string' || value == null) {
    callback(new Error('请输入分钟数'))
  } else if (value < 0) {
    callback(new Error('输入分钟数必须大于或等于0'))
  } else if (value >= 100000) {
    callback(new Error('输入分钟数必须小于100000'))
  } else {
    callback()
  }
}
// 这里引入修改过的video模块并注册
import Video from "../quill/video.js";
Quill.register(Video, true);
export default {
  name: "contentOperation",
  components: {
    quillEditor
  },
  data () {
    let that = this;
    return {
      categoryList: [],
      pageType: this.$route.query.type,
      headers: {
        Authorization: getToken()
      },
      content: null,
      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);
                }
              }
            }
          }
        }
      },
      form: {
        name: null,
        suitableUser: null,
        date: null,
        startDate: null,
        endDate: null,
        totalPrice: null,
        discountPrice: null,
        purchaseMinutes: null,
        giveMinutes: null,
        coverImg: null,
        detail: null
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" }
        ],
        suitableUser: [{ required: true, message: "请选择适用范围", trigger: "change" }],
        date: [{ required: true, message: '请选择有效期', trigger: 'change' }],
        totalPrice: [{ required: true, validator: validPrice, trigger: 'blur' }],
        discountPrice: [{ required: true, validator: validPrice, trigger: 'blur' }],
        purchaseMinutes: [{ required: true, validator: validMinutes, trigger: 'blur' }],
        giveMinutes: [{ required: true, validator: validMinutes, trigger: 'blur' }],
        coverImg: [
          { required: true, message: "请选择活动图", trigger: "blur" }
        ],
        detail: [{ required: true, message: "请编辑活动内容", trigger: "blur" }]
      },
      imageSize: null
    };
  },
  created () { },
  mounted () {
    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];
    },
    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") {
            let form = this.form
            let params = {
              name: form.name,
              suitableUser: form.suitableUser,
              startDate: form.date[0],
              endDate: form.date[1],
              totalPrice: form.totalPrice,
              discountPrice: form.discountPrice,
              purchaseMinutes: form.purchaseMinutes,
              giveMinutes: form.giveMinutes,
              coverImg: form.coverImg,
              detail: form.detail,
              delFlag: false
            }
            // return false
            getActivitieMerge(params).then(res => {
              this.messageTips("添加", res);
            });
          }
        } else {
          this.$nextTick(() => {
            let isError = document.getElementsByClassName('is-error')
            isError[0].scrollIntoView({
              block: 'center',
              behavior: 'smooth',
            })
          })
          return false;
        }
      });
    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.$store.dispatch('delVisitedViews', this.$route)
        this.$router.push({
          path: "/sysBasics/entryActivities"
        });
      } else {
        this.$message.error(res.msg);
      }
    },
    onCancel () {
      this.$store.dispatch('delVisitedViews', this.$route)
      this.$router.push({
        path: "/sysBasics/entryActivities"
      });
    },
    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 {
        getActivitieQuery({ id: this.$route.query.id }).then(res => {
          if (res.code == 200) {
            let result = res.data;
            let form = this.form;
            this.form = {
              name: result.name,
              suitableUser: result.suitableUser,
              date: [result.startDate, result.endDate],
              startDate: result.startDate,
              endDate: result.endDate,
              totalPrice: result.totalPrice,
              discountPrice: result.discountPrice,
              purchaseMinutes: result.purchaseMinutes,
              giveMinutes: result.giveMinutes,
              coverImg: result.coverImg,
              detail: result.detail,
            };
          }
        });
      }
    },
    handleAvatarSuccess (res, file) {
      load.endLoading()
      this.form.coverImg = res.data.url;
    },
    beforeAvatarUpload (file) {
      const imageType = {
        "image/png": true,
        "image/jpeg": true,
        "image/gif": true
      };
      const isImage = imageType[file.type];
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      if (isImage && isLt2M) { // 判断是否满足条件
        load.startLoading()
      }
      return isImage && isLt2M;
    },
    onEditorChange ({ quill, html, text }) {
      this.form.detail = html;
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill;
    }
  }
};
</script>
<style lang="scss" scoped>
.m-container {
  min-width: 100%;
}
.el-input {
  width: 400px;
}
::v-deep .ql-editor {
  min-height: 300px;
  padding: 0;
}
::v-deep .ql-container .ql-editor {
  max-height: 500px;
}
.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;
}
::v-deep .el-tree-node__content {
  height: 40px !important;
}
::v-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: 240px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
::v-deep .el-date-editor {
  width: 400px;
}
.avatar {
  width: 240px;
  height: 120px;
  display: block;
}
.ivu-upload {
  display: none;
}
</style>