<template>
  <div class="editor">
    <HeaderEdit :goback="dialogSave" @saveThemeSuccess="showPreView=true" />
    <section class="section">
      <Overview class="overview" />
      <div class="canvas-wrap" id="canvas-wrap">
        <div id="customCanvas"
          :style="{ width: canvasWidth + 'px', height: (canvasHeight) + 'px',position:'absolute',top:'5%'}">
          <!-- 警告：
           v-if这里不能使用，使用后，编辑页面则canvas不自动触发，因为canvas标签已经不显示
           v-show用这个标签，如果其他页面有canvas动画，则点击编辑进去后，控制台会报错误，非法更改值错误
           -->
          <elab-canvas v-show="animatedNameGlobal!=''" :width="canvasWidth" :height="(canvasHeight)"
            :cstyle="`position: absolute;z-index:99999; pointer-events:none;width:100%;height:100%`"
            :background="'transparent'" :type="animatedNameGlobal"></elab-canvas>
          <elab-background-canvas v-if="animatedNameBackgroundGlobal!=''" :width="canvasWidth" :height="(canvasHeight)"
            :cstyle="`position: absolute;z-index:1; pointer-events:none`" :background="'transparent'"
            :type="animatedNameBackgroundGlobal"></elab-background-canvas>

        </div>
        <Page ref="page" id="canvasPage" :elements="editorPage.elements" :editorElement="element"
          :selectedElement="selectedElement" :style="{ width: canvasWidth + 'px', height: (canvasHeight+100) + 'px',
              backgroundColor: bodyBackgroundColor,overflow:'hidden'}" />
        <div v-if="this.gridTempField"
          :style="{'background-image':'linear-gradient(90deg,rgba(204,204,204,0.3) 10%,transparent 0), linear-gradient(rgba(204,204,204,0.3) 10%,transparent 0)',
              'background-size':'15px 15px', 'z-index':100000,width: canvasWidth + 'px', height: (canvasHeight+100) + 'px'}"
          style="position: absolute;left: 0;top: 5%;z-index: 9999;pointer-events: none"></div>
      </div>
      <div class="control-panel">
        <div class="funcs">
          <el-tooltip effect="dark" content="新建文本" placement="left">
            <button class="func el-icon-edit" @click="togglePanel(1)" :class="{ active: panelState === 1 }"></button>
          </el-tooltip>
          <el-tooltip effect="dark" content="新建素材" placement="left">
            <button class="func el-icon-picture" @click="togglePanel(2)" :class="{ active: panelState === 2 }"></button>
          </el-tooltip>
          <el-tooltip effect="dark" content="新建轮播" placement="left">
            <button class="func el-icon-more" @click="togglePanel(3)" :class="{ active: panelState === 3 }"></button>
          </el-tooltip>
          <!--<el-tooltip  effect="dark" content="播放动画" placement="left">-->
          <!--<button class="func el-icon-caret-right" @click="playAnimate"></button>-->
          <!--</el-tooltip>-->
          <el-tooltip effect="dark" content="桌面画布" placement="left">
            <button class="func el-icon-document" @click="togglePanel(0)"
              :class="{ active: panelState === 0 }"></button>
          </el-tooltip>
          <el-tooltip effect="dark" content="保存" placement="left">
            <button class="func el-icon-upload" @click="save"></button>
          </el-tooltip>
        </div>
        <div class="wrapper custom-scrollbar">
          <!-- 设置背景 0 -->
          <div class="panel panel-bg">
            <div class="clearfix" v-if="panelTabState !== 1 && panelTabState !== 3">
              <el-button class="btn" type="success" @click="panelTabState = 1">更换背景</el-button>
              <el-button class="btn" type="danger" @click="cleanBG">移除背景</el-button>

              <div class="item">
                <label>设置作品信息</label>
                <div class="content">
                  <el-input placeholder="请输入标题" v-model="title" clearable>
                  </el-input>
                </div>
                <div class="content">
                  <el-input placeholder="请输入描述" v-model="description" clearable>
                  </el-input>
                </div>
              </div>

              <div class="item">
                <label>画布背景色</label>
                <div class="content">
                  <!--<el-input class="input"-->
                  <!--type="color"-->
                  <!--v-model="bodyBackgroundColor"></el-input>-->
                  <el-color-picker v-model="bodyBackgroundColor"></el-color-picker>
                </div>
              </div>
              <div class="item">
                <label>IM背景色</label>
                <div class="content">
                  <!--<el-input class="input"-->
                  <!--type="color"-->
                  <!--v-model="bodyBackgroundColor"></el-input>-->
                  <el-color-picker @change="IMChange" v-model="bgc" show-alpha></el-color-picker>
                </div>
              </div>
              <div class="item">
                <label>IM按钮颜色</label>
                <div class="content">
                  <!--<el-input class="input"-->
                  <!--type="color"-->
                  <!--v-model="bodyBackgroundColor"></el-input>-->
                  <el-color-picker @change="IMChange" v-model="btnColor" show-alpha></el-color-picker>
                </div>
              </div>
              <div class="item">
                <label>画布宽度</label>
                <div class="content">
                  <el-input-number v-model="canvasWidth" :disabled="true">
                  </el-input-number>
                </div>
              </div>
              <div class="item">
                <label>画布高度</label>
                <div class="content">
                  <el-input-number v-model="canvasHeight">
                  </el-input-number>
                </div>
              </div>

              <div class="clearfix" v-if="panelTabState !== 1 && panelTabState !== 3">
                <label>屏飘动效</label>
                <div class="content" :xxx="`animatedNameGlobal`">
                  <div
                    style="background: #EBEDEF;display: inline-flex; width:33.3%;overflow: hidden;text-align: center; cursor: pointer"
                    v-for="(item,index) in animateGlobalList">
                    <div v-model="animatedNameGlobal" @click="checkGlobalAnimation(item)" :title="item.name" :style="{'font-size': '12px',color: animatedNameGlobal==item.id? 'white':'#999999','letter-spacing': 0, width:'100%',
                    'word-break':'keep-all',padding: '20px','background': animatedNameGlobal===item.id? 'green':'',
               'font-weight': animatedNameGlobal===item.id? 'bold':'norm'
               }">{{item.name}}</div>
                  </div>
                </div>
              </div>

              <div class="clearfix" v-if="panelTabState !== 1 && panelTabState !== 3">
                <label>背景动效</label>
                <div class="content" :xxx="`animatedNameBackgroundGlobal`">
                  <div
                    style="background: #EBEDEF;display: inline-flex; width:33.3%;overflow: hidden;text-align: center; cursor: pointer"
                    v-for="(item,index) in animateBackgroundGlobalList">
                    <div v-model="animatedNameBackgroundGlobal" @click="checkBackgroundGlobalAnimation(item)"
                      :title="item.name" :style="{'font-size': '12px',color: animatedNameBackgroundGlobal==item.id? 'white':'#999999','letter-spacing': 0, width:'100%',
                    'word-break':'keep-all',padding: '20px','background': animatedNameBackgroundGlobal===item.id? 'green':'',
               'font-weight': animatedNameBackgroundGlobal===item.id? 'bold':'norm'
               }">{{item.name}}</div>
                  </div>
                </div>
              </div>

              <div class="item">
                <label>背景音乐</label>
                <div class="content">
                  <AudioPanel class="ele"></AudioPanel>
                </div>
              </div>

            </div>
            <div class="clearfix" v-if="panelTabState === 1">
              <ImgPanel :selectedImg="addBG" />
            </div>

            <div class="clearfix" v-if="panelTabState === 3">
              <div style="margin-top: 5px; height:100%;vertical-align: middle;padding-right:10px">
                <div style="display: inline-flex; overflow: hidden;">
                  <div style="font-size: 14px;color: #999999;letter-spacing: 0; word-break:keep-all;width:100%">
                    组合对齐布局
                  </div>
                </div>
                <div style="margin-top: 10px">
                  <div style="display: inline-flex; overflow: hidden;width: 14%; cursor: pointer; text-align: center">
                    <div @click="toLeft" title="左对齐"
                      :style="{'font-size': '12px','letter-spacing': 0, 'word-break':'keep-all','text-align':'center','width':'100%'}">
                      <img src="http://yun-image.elab-plus.com/images/tfb/icon_left2.png" width="20" height="20" />
                    </div>

                  </div>
                  <div title="水平居中对齐"
                    style="display: inline-flex; overflow: hidden;width: 14%; cursor: pointer;text-align: center"
                    @click="toCenter">
                    <div
                      :style="{'font-size': '12px','letter-spacing': 0, 'word-break':'keep-all','text-align':'center','width':'100%'}">
                      <img src="http://yun-image.elab-plus.com/images/tfb/horizontal_center.png" width="20"
                        height="20" />
                    </div>

                  </div>
                  <div title="右对齐" style="display: inline-flex;cursor: pointer;width: 14%; text-align: center"
                    @click="toRight">
                    <div
                      :style="{'font-size': '12px','letter-spacing': 0, 'word-break':'keep-all','text-align':'center','width':'100%'}">
                      <img src="http://yun-image.elab-plus.com/images/tfb/icon_right2.png" width="20" height="20" />
                    </div>
                  </div>

                  <div style="display: inline-flex; overflow: hidden;width: 14%; cursor: pointer; text-align: center">
                    <div @click="toTop" title="上对齐"
                      :style="{'font-size': '12px','letter-spacing': 0, 'word-break':'keep-all','text-align':'center','width':'100%'}">
                      <img src="http://yun-image.elab-plus.com/images/tfb/icon_top.png" width="20" height="20" />
                    </div>

                  </div>
                  <div title="垂直居中对齐"
                    style="display: inline-flex; overflow: hidden;width: 14%; cursor: pointer;text-align: center"
                    @click="toVertialCenter">
                    <div
                      :style="{'font-size': '12px','letter-spacing': 0, 'word-break':'keep-all','text-align':'center','width':'100%'}">
                      <img src="http://yun-image.elab-plus.com/images/tfb/vertical_center.png" width="20" height="20" />
                    </div>

                  </div>
                  <div title="下对齐" style="display: inline-flex;cursor: pointer;width: 14%; text-align: center"
                    @click="toBottom">
                    <div
                      :style="{'font-size': '12px','letter-spacing': 0, 'word-break':'keep-all','text-align':'center','width':'100%'}">
                      <img src="http://yun-image.elab-plus.com/images/tfb/icon_down.png" width="20" height="20" />
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>
          <!-- 添加文字 1 -->
          <div class="panel panel-text" v-if="panelState === 1">
            <div class="btn" @click="addTextElement('title')" style="font-size: 32px; font-weight: bold;">插入标题</div>
            <div class="btn" @click="addTextElement('plain')">插入文本</div>
            <div class="btn" @click="addTextElement('frame')">插入方框</div>
          </div>
          <!-- 添加元素 2 -->
          <div class="panel panel-element clearfix" v-if="panelState === 2">
            <ImgPanel :selectedImg="addPicElement" />
          </div>
          <!-- 添加多图上元素 3 -->
          <div class="panel panel-element clearfix" v-if="panelState === 3">
            <ImgPanel :selectedImg="addMorePicElement" :ismultiple="true" />
          </div>
          <!-- 图层编辑面板 -->
          <EditPanel :element="element" :panelState="panelState" v-if="panelState > 10" />
        </div>
      </div>
    </section>
    <PreView :itemId="itemId" @hideView="showPreView=false" v-if="showPreView" />
  </div>
</template>

<script>
import tools from "../../util/tools";
import Overview from "./overview";
import Page from "../../components/Page";
import PicPicker from "../../components/PicturePicker";
import PreView from "../../components/PreView";
import HeaderEdit from "../../components/HeaderEdit";
import EditPanel from "../../components/EditPanel";
import SvgPanel from "../../components/SvgPanel";
import ImgPanel from "../../components/ImgPanel";
import appConst from "../../util/appConst";
import AudioPanel from "../../components/AudioPanel";
import html2canvas from "html2canvas";
import { uploadBase64 } from "../../util/http";
import elabCanvas from "../../util/canvas/elabCanvas.vue";
import elabBackgroundCanvas from "../../util/canvas/elabBackgroundCanvas";
const $ = require("jquery");

export default {
  data() {
    return {
      itemId: null,
      panelState: 0,
      canvasWidth: 750,
      canvasHeight: 0,
      bodyBackgroundColor: "rgba(255,255,255,0)",
      bgc: "#B1C096",
      btnColor: "#5f8a61",
      title: "",
      description: "",
      dialogSaveBeforeBack: false,
      picBase64: "",
      http: appConst.BACKEND_DOMAIN,
      releaseUrl: "",
      showPreView: false,
      isLoadingPreview: false,
      panelTabState: 0,
      animatedNameGlobal: "",
      animatedCustom: false,
      globalAnimatedTag: false,
      animatedNameGlobalDelayClick: false,
      animateGlobalList: [
        { id: "Snow", name: "下雪", type: 0 },
        { id: "Bubble", name: "冒泡", type: 0 },
        { id: "Flower", name: "樱花", type: 0 },
        { id: "Rain", name: "下雨", type: 0 },
        { id: "Bubble2", name: "飞沙", type: 0 },
        { id: "Particles", name: "粒子", type: "0" },
        { id: "Circle", name: "圆圈", type: "0" },
        { id: "FlowField", name: "流场", type: "0" },
        { id: "cloud", name: "云飘", type: "0" },
        { id: "nephelo", name: "雾霾", type: "0" }
      ],
      animateBackgroundGlobalList: [
        { id: "Smoke", name: "烟雾", type: 1 },
        { id: "Wave", name: "波浪", type: 2 },
        // {id: 'WaterRipple', name: '水波', type: 3},
        { id: "Bubble2", name: "飞沙", type: 0 },
        { id: "Particles", name: "粒子", type: "0" },
        { id: "Circle", name: "圆圈", type: "0" },
        { id: "FlowField", name: "流场", type: "0" },
        { id: "ColorRandom", name: "渐变色", type: "0" }
      ],
      animatedNameBackgroundGlobal: "",
      animatedBackgroundCustom: false,
      globalAnimatedBackgroundTag: false,
      animatedNameBackgroundGlobalDelayClick: false,
      gridTempField: false
    };
  },
  watch: {
    picBase64() {},
    element() {
      let ele = this.$store.state.editor.editorElement;
      let type = ele ? ele.type : "null";
      this.panelTabState = 0;

      var length = this.$store.state.editor.complexEditorElement.length;
      if (length > 1) {
        type = "group";
        this.panelTabState = 3;
      }

      switch (type) {
        case "text":
          this.panelState = 11;
          break;
        case "icon":
        case "pic":
          this.panelState = 12;
          break;
        case "audio":
          this.panelState = 12;
          break;
        case "morePic":
          this.panelState = 13;
          break;
        case "frame":
          this.panelState = 14;
          break;
        case "group":
          this.panelState = 0;
        default:
          this.panelState = 0;
      }
    },
    "$store.state.editor.complexEditorElement": function() {
      var complexEditorElement = this.$store.state.editor.complexEditorElement;
      if (complexEditorElement.length == 0 && this.panelTabState == 3) {
        this.panelTabState = 0;
      }
    }
  },
  computed: {
    themeId() {
      return this.$store.state.editor.editorTheme._id;
    },
    editorPage() {
      this.bgc = this.$store.state.editor.editorTheme.bgc || "#B1C096";
      this.btnColor =
        this.$store.state.editor.editorTheme.btnColor || "#5f8a61";
      this.bodyBackgroundColor =
        this.$store.state.editor.editorTheme.bodyBackgroundColor ||
        "rgba(255,255,255,0)";
      this.canvasWidth =
        this.$store.state.editor.editorTheme.canvasWidth || 750;
      this.canvasHeight = this.$store.state.editor.editorTheme.canvasHeight;
      this.description = this.$store.state.editor.editorTheme.description;
      this.title = this.$store.state.editor.editorTheme.title;
      this.animatedNameGlobal =
        this.$store.state.editor.editorTheme.animatedNameGlobal || "";
      this.animatedNameBackgroundGlobal =
        this.$store.state.editor.editorTheme.animatedNameBackgroundGlobal || "";
      this.gridTempField = this.$store.state.editor.gridTempField;
      return this.$store.state.editor.editorPage;
    },
    element() {
      let ele = this.$store.state.editor.editorElement;
      return ele || {};
    },
    picList() {
      return this.$store.state.editor.picList;
    },
    complexEditorElement() {
      return this.$store.state.editor.complexEditorElement;
    }
  },
  methods: {
    dialogSave() {
      // return Promise.resolve().then(() => this.save()).then(() => this.$router.replace('spaList'))
      if (!window.hasSaveFlag) {
        this.$confirm(
          "请确保已经将修改的内容保存，否则页面将丢失。是否确认退出编辑？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            window.hasSaveFlag = true;
            return Promise.resolve().then(() =>
              this.$router.replace("spaList")
            );
          })
          .catch(() => {});
      } else {
        return Promise.resolve().then(() => this.$router.replace("spaList"));
      }
    },
    getPicList(_id) {
      this.$store.dispatch("getPicListByThemeId", _id);
    },
    uploadImage(data) {
      this.$store.dispatch("savePic", {
        filePath: data["filePath"],
        themeId: this.themeId,
        width: data["width"],
        height: data["height"]
      });
    },
    addPicElement(ele) {
      // if (ele) {
      let obj = {};
      obj.type = "pic";
      obj.top = document.getElementById("canvas-wrap").scrollTop;
      obj.left = 0;
      obj.width = ele.width;
      obj.height = ele.height;
      obj.imgSrc = ele.filePath;
      obj.loop = ele.loop;
      this.$store.dispatch("addElement", obj);
      // } else {
      //   this.$store.dispatch('addElement', this.element)
      // }
      this.element.type = "pic";
    },
    //
    addMorePicElement(ele) {
      // if (ele) {
      let obj = {};
      obj.type = "morePic";
      obj.top = document.getElementById("canvas-wrap").scrollTop;
      obj.left = 0;
      obj.width = ele.morePic[0].width;
      obj.height = ele.morePic[0].height;
      obj.imgSrc = ele.filePath;
      obj.morePic = ele.morePic;
      obj.loop = ele.loop;
      this.$store.dispatch("addElement", obj);
      this.element.type = "morePic";
    },
    addBG(file) {
      this.$store.dispatch("addBGElement", {
        type: "bg",
        imgSrc: file.filePath
      });
    },
    cleanBG() {
      if (this.globalAnimatedTag) {
        this.$message.error("当前有背景动画，该背景图不能移除");
        return;
      }
      this.$store.dispatch("cleanBG");
    },
    cleanEle() {
      this.$store.dispatch("cleanEle", this.element);
    },
    addTextElement(type) {
      let param = {};
      param.top = document.getElementById("canvas-wrap").scrollTop;
      param["type"] = "text";
      param["text"] = "请输入文本";
      param["width"] = 300;
      param["lineHeight"] = 1.5;
      param["backgroundColor"] = "";
      param["verticalAlign"] = "top";
      param["display"] = "block";
      param["textIndent"] = "0.0";
      param["letterSpacing"] = "0.0";
      param["allTransparent"] = "";
      param["nodeId"] = "Id" + Math.random();
      switch (type) {
        case "plain":
          break;
        case "title":
          param["fontSize"] = 32;
          param["fontWeight"] = "bold";
          param["textAlign"] = "center";
          break;
        case "frame":
          param["type"] = "frame";
          param["text"] = "";
          param["width"] = this.canvasWidth;
          param["border"] = "1px solid #000";
          param["height"] = 500;
          break;
        default:
      }
      this.$store.dispatch("addElement", param);
    },
    playAnimate() {
      this.$store.dispatch("playAnimate");
    },
    base64ToBlob(urlData) {
      var arr = urlData.split(",");
      var mime = arr[0].match(/:(.*?);/)[1] || "image/png";
      // 去掉url的头，并转化为byte
      var bytes = window.atob(arr[1]);
      // 处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length);
      // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
      var ia = new Uint8Array(ab);

      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }

      return new Blob([ab], {
        type: mime
      });
    },
    async save() {
      var loading = this.$loading({
        lock: true,
        text: "模板保存中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      if (!hasSaveFlag) {
        $(".animated").css("animation-name", "null");
        $(".animated>div").css("animation-name", "null");
        $(".animated span").css({
          animationDelay: "0s",
          animationDuration: "0s"
        });
        await html2canvas(document.querySelector("#canvasPage"), {
          useCORS: true,
          scale: 0.5,
          height: 1334,
          logging: false //日志开关， 便于查看html2canvas的内部执行流程
        })
          .then(async canvas => {
            var result = await uploadBase64({ base64Str: canvas.toDataURL() })
              .then(result => {
                if (result.data.success) {
                  this.$store.state.editor.editorTheme.cover =
                    result.data.single.filePath;
                } else {
                  this.$message.error("封面图片上传失败！");
                }
              })
              .catch(() => {
                this.$message.error("封面图片上传失败！");
              });
          })
          .catch(err => {
            this.$message.error(err);
          });
      }
      this.$store.state.editor.editorTheme.bgc = this.bgc;
      this.$store.state.editor.editorTheme.btnColor = this.btnColor;
      this.$store.state.editor.editorTheme.bodyBackgroundColor =
        this.bodyBackgroundColor || "rgba(255,255,255,0)";
      this.$store.state.editor.editorTheme.canvasWidth =
        this.canvasWidth || 750;
      this.$store.state.editor.editorTheme.canvasHeight = this.canvasHeight;
      this.$store.state.editor.editorTheme.title = this.title;
      this.$store.state.editor.editorTheme.description = this.description;
      this.$store.state.editor.editorTheme.animatedNameGlobal =
        this.animatedNameGlobal || "";
      this.$store.state.editor.editorTheme.animatedNameBackgroundGlobal =
        this.animatedNameBackgroundGlobal || "";
      this.editorPage.elements.forEach(function(element) {
        if (element.type == "text") {
          var height = window
            .getComputedStyle(document.getElementById(element.nodeId))
            .height.replace("px", "");
          element.height = height;
        } else if (element.type == "frame") {
          element.children.forEach(function(_element) {
            if (_element.type == "text") {
              var height = window
                .getComputedStyle(document.getElementById(_element.nodeId))
                .height.replace("px", "");
              _element.height = height;
            }
          });
        }
      });
      return this.$store
        .dispatch(
          "saveTheme",
          tools.vue2json(this.$store.state.editor.editorTheme)
        )
        .then(() => {
          loading.close();
          this.$message({
            message: "保存成功",
            type: "success"
          });
        })
        .catch(() => {
          loading.close();
        });
    },
    deploy() {
      this.isLoadingPreview = true;
      this.$store
        .dispatch(
          "saveTheme",
          tools.vue2json(this.$store.state.editor.editorTheme)
        )
        .then(() => {
          setTimeout(() => {
            this.showPreView = true;
            this.isLoadingPreview = false;
          }, 1000);
        });
    },
    selectedElement(element) {
      this.$store.dispatch("setEditorElement", element);
    },
    deleteListener(event) {
      if (
        event.keyCode === 8 &&
        event.target.nodeName !== "INPUT" &&
        event.target.nodeName !== "TEXTAREA"
      ) {
        this.deleteElement();
      }
    },
    deleteElement() {
      this.$store.dispatch("deleteSelectedElement");
    },
    togglePanel(code) {
      this.panelState = code;
      if (code === 0) {
        this.panelTabState = 0;
        this.$store.dispatch("setEditorElement", null);
      }
    },
    checkGlobalAnimation(item) {
      if (this.animatedNameGlobalDelayClick) {
        return;
      }
      this.animatedNameGlobalDelayClick = true;
      if (this.animatedNameGlobal != item.id) {
        this.animatedNameGlobal = item.id;
        this.animatedCustom = item.type == 0 ? false : true;
      } else {
        this.animatedNameGlobal = "";
      }
      setTimeout(() => {
        this.animatedNameGlobalDelayClick = false;
      }, 500);
    },
    checkBackgroundGlobalAnimation(item) {
      if ("WaterRipple" == item.id) {
        this.globalAnimatedTag = true;
        if (document.querySelectorAll(".bg-layer").length > 0) {
          if (this.animatedNameBackgroundGlobal != item.id) {
            this.animatedNameBackgroundGlobal = item.id;
            this.animatedBackgroundCustom = item.type == 0 ? false : true;
          } else {
            this.globalAnimatedTag = false;
            this.animatedNameBackgroundGlobal = "";
          }
        } else {
          this.$message.error("请设置背景图片");
        }
      } else {
        if (this.animatedNameBackgroundGlobal != item.id) {
          this.animatedNameBackgroundGlobal = item.id;
          this.animatedBackgroundCustom = item.type == 0 ? false : true;
        } else {
          this.animatedNameBackgroundGlobal = "";
        }
      }
    },
    toLeft() {
      let complexEditorElement = this.complexEditorElement;
      let arr = complexEditorElement.map(item => {
        return item.left;
      });
      let min = Math.min.apply(null, arr);
      complexEditorElement.forEach(ele => {
        ele.left = min;
      });
    },
    toCenter() {
      let complexEditorElement = this.complexEditorElement;
      let arr = complexEditorElement.map(item => {
        return item.left;
      });
      let total = 0;
      for (let i = 0; i < arr.length; i++) {
        total += arr[i];
      }
      let p = total / arr.length;
      complexEditorElement.forEach(ele => {
        ele.left = p;
      });
    },
    toRight() {
      let complexEditorElement = this.complexEditorElement;
      let arr = complexEditorElement.map(item => {
        return item.width + item.left;
      });
      let max = Math.max.apply(null, arr);
      complexEditorElement.forEach(ele => {
        ele.left = max - ele.width;
      });
    },
    toTop() {
      let complexEditorElement = this.complexEditorElement;
      let arr = complexEditorElement.map(item => {
        return item.top;
      });
      let min = Math.min.apply(null, arr);
      complexEditorElement.forEach(ele => {
        ele.top = min;
      });
    },
    toVertialCenter() {
      let complexEditorElement = this.complexEditorElement;
      let arr = complexEditorElement.map(item => {
        return item.top;
      });
      let total = 0;
      for (let i = 0; i < arr.length; i++) {
        total += arr[i];
      }
      let p = total / arr.length;
      complexEditorElement.forEach(ele => {
        ele.top = p;
      });
    },
    toBottom() {
      let complexEditorElement = this.complexEditorElement;
      let arr = complexEditorElement.map(item => {
        return item.height + item.top;
      });
      let max = Math.max.apply(null, arr);
      complexEditorElement.forEach(ele => {
        ele.top = max - ele.height;
      });
    },
    IMChange() {
      this.$store.state.editor.editorTheme.bgc = this.bgc;
      this.$store.state.editor.editorTheme.btnColor = this.btnColor;
    }
  },
  components: {
    Overview,
    Page,
    PicPicker,
    appConst,
    PreView,
    HeaderEdit,
    EditPanel,
    SvgPanel,
    ImgPanel,
    AudioPanel,
    elabCanvas,
    elabBackgroundCanvas
  },
  mounted() {
    this.$store.state.editor.editorElement = {};
    this.$store.state.editor.editorPage = {};
    this.$store.state.editor.editorTheme = {};
    this.itemId = this.$route.query.itemId;
    if (this.itemId) {
      if (!this.pages) {
        this.$store.dispatch("getPageByThemeId", this.itemId);
      }
      this.getPicList(this.itemId);
    } else {
      this.$store.dispatch("createTheme");
      this.$store.dispatch("addPage");
      this.$store.dispatch("cleanPicList");
    }
    document.addEventListener("keyup", this.deleteListener);
    window.onbeforeunload = () => false;
  },
  destroyed() {
    document.removeEventListener("keyup", this.deleteListener);
    window.onbeforeunload = null;
  }
};
</script>

<style lang="less" scoped>
.editor {
  background-color: #eaedef;
  position: relative;
  height: 100%;
  /*overflow: hidden;*/
  user-select: none;
  min-width: 1270px;
}
.section {
  position: absolute;
  left: 0;
  right: 0;
  top: 60px;
  bottom: 0;
  overflow: hidden;
}

.overview {
  position: absolute !important;
  left: 0;
  width: 160px;
  height: 100%;
  z-index: 10;
}
.canvas-wrap {
  position: absolute;
  height: 100%;
  width: 820px;
  left: 42%;
  transform: translateX(-45%);
  overflow: scroll;
  overflow-x: hidden;
}
.canvas {
  position: absolute !important;
  top: 5%;
  border: 1px solid #ccc;
  box-shadow: 0px 2px 30px 5px rgba(0, 0, 0, 0.2);
  box-sizing: content-box;
  margin-bottom: 200px;
}
.tool-bar {
  position: absolute;
  width: 250px;
  height: 30px;
  margin: 0 40px;
  line-height: 30px;
  top: 538px;
  text-align: center;
  color: #acb5b3;
  font-size: 12px;
  border: 1px solid #ccc;
  background-color: #fff;
  // cursor: ns-resize;
}
.control-panel {
  position: absolute;
  width: 300px;
  height: 100%;
  right: 0;
  top: 0;
  border-left: 1px solid #d6d6d6;
  background-color: #ececec;
  z-index: 10;
  .funcs {
    position: absolute;
    left: -50px;
    top: 0;
    width: 50px;
    .func {
      color: #b2bcba;
      background: #fff;
      cursor: pointer;
      margin-top: 20px;
      display: block;
      width: 50px;
      height: 50px;
      border: 1px solid #d6d6d6;
      border-radius: 3px 0px 0px 3px;
      &:hover {
        color: #000;
      }
      &.active {
        border-right: 1px solid #ececec;
        background-color: #ececec;
        color: #000;
      }
    }
  }
  .wrapper {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    position: relative;
  }
  .panel {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    padding: 10px;
    z-index: 2;
    background-color: #ececec;
    overflow-y: auto;
  }

  .panel-bg {
    .btn {
      float: left;
      width: 48%;
      margin-left: 1%;
      margin-right: 1%;
    }
    .bgs {
      float: left;
      width: 80px;
      height: 80px;
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
      margin: 5px 5px;
      &:hover {
        border: 2px solid #18ccc0;
        cursor: pointer;
      }
    }
  }

  .panel-text {
    .btn {
      height: 50px;
      line-height: 50px;
      text-align: center;
      border: 2px solid transparent;
      &:hover {
        cursor: pointer;
        border-color: #04b9c4;
      }
    }
  }
  .panel-element {
    .ele {
      float: left;
      width: 80px;
      height: 80px;
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
      margin: 5px 5px;
      &:hover {
        border: 2px solid #18ccc0;
        cursor: pointer;
      }
    }
  }
}

/* 2018/07/23 所有前台自定义字体，需要放七牛云服务器上，暂时放这个样式文件里面 */
@font-face {
  font-family: 思源黑体细;
  src: url("http://yun-image.elab-plus.com/new/noto_light.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 思源黑体常规;
  src: url("http://yun-image.elab-plus.com/new/noto_regular.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 思源黑体中;
  src: url("http://yun-image.elab-plus.com/new/noto_medium.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 思源黑体粗;
  src: url("http://yun-image.elab-plus.com/new/noto_bold.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 思源宋体细;
  src: url("http://yun-image.elab-plus.com/new/source_light.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 思源宋体常规;
  src: url("http://yun-image.elab-plus.com/new/source_regular.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 思源宋体中;
  src: url("http://yun-image.elab-plus.com/new/source_medium.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 思源宋体粗;
  src: url("http://yun-image.elab-plus.com/new/source_bold.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 思源宋体极粗;
  src: url("http://yun-image.elab-plus.com/new/source_heavy.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 手写体;
  src: url("http://yun-image.elab-plus.com/new/shouxieti.ttf")
    format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 站酷高端黑;
  src: url("http://yun-image.elab-plus.com/zkgdh.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 站酷酷黑;
  src: url("http://yun-image.elab-plus.com/zkkh.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 站酷文艺体;
  src: url("http://yun-image.elab-plus.com/wenyi.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 酷站小黑LOGO体;
  src: url("http://yun-image.elab-plus.com/logoti.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: "ZCOOL_Italic";
  src: url("http://yun-image.elab-plus.com/ZCOOL_Italic.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 旁门正道标题体;
  src: url("http://yun-image.elab-plus.com/pmzd.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 杨任东竹石体细;
  src: url("http://yun-image.elab-plus.com/yzd_light.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 杨任东竹石体常规;
  src: url("http://yun-image.elab-plus.com/yzd_regular.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 杨任东竹石体粗;
  src: url("http://yun-image.elab-plus.com/yzd_heavy.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}
</style>
