<template>
  <header class="header">
    <div class="reset-btn">
      <i class="el-icon-arrow-left" @click="goback"></i>
      <span class="reset-title">{{title || '返回作品'}}</span>
      <i class="el-icon-edit edit-title" @click="editTitle"></i>
    </div>
    <div class="tools">
      <div class="next_return">
        <div class="return" title="撤销" @click="revocation" :style="`opacity:${operationList.length>1?'1':'.3'}`">
          <img class="retutn_icon" src="../assets/images/button_return.png" alt="">
          <span>撤销</span>
        </div>
        <div class="return" title="恢复" @click="recover" :style="`opacity:${nextList.length>0?'1':'.3'}`">
          <img class="retutn_icon" src="../assets/images/button_next.png" alt="">
          <span>恢复</span>
        </div>
        <div class="return" title="分享设置" @click="shareSetting">
          <img class="retutn_icon" src="../assets/images/share_setting_edit_nor.png" alt="">
          <span>分享设置</span>
        </div>
        <div class="return" title="保存" @click="save">
          <img class="retutn_icon" src="../assets/images/save_edit_nor.png" alt="">
          <span>保存</span>
        </div>
      </div>
    </div>
    <!-- <div class="next_return">
      <span class="return" title="撤销" @click="revocation" :style="`opacity:${operationList.length>1?'1':'.3'}`"></span>
      <span class="next" title="恢复" @click="recover" :style="`opacity:${nextList.length>0?'1':'.3'}`"></span>

    </div>
    <el-button @click="grid" class="preview " type="primary" style="margin-left: 50px;">网格参考线</el-button>

    <div class="right-panel">
      <el-button @click="deploy" class="preview" type="primary" :loading="loading">预览</el-button> -->
    <!--<el-button @click="psd"-->
    <!--class="preview"-->
    <!--type="primary"-->
    <!--:loading="loading" style="margin-right: 20px">PSD导入</el-button>-->
    <!--<el-upload-->
    <!--class="upload-demo"-->
    <!--:action="`${appConst}/api/pages/psd`"-->
    <!--accept="A/.psd"-->
    <!--:on-change="uploadFn">-->
    <!--<el-button size="small" type="primary">psd文件导入</el-button>-->
    <!--<div slot="tip" class="el-upload__tip">只能上传psd文件</div>-->
    <!--</el-upload>-->
    <!-- <form id="upload" enctype='multipart/form-data'>
        <input type="hidden" id="itemId" />
        <input type="file" id="psdFile" name="image" @change="uploadFn">

      </form>
    </div> -->
    <!-- 分享设置 -->
    <ShareSetting v-if="isShareSetting" :close="closeShare" :shareModel="shareModel"></ShareSetting>
  </header>
</template>

<script>
import tools from "../util/tools";
import api from "../api/editor";

import ShareSetting from "./ShareSetting";
var time = null;
export default {
  props: {
    goback: Function,
    save: Function,
    title: "",
    shareModel: ""
  },
  components: {
    ShareSetting
  },
  data() {
    return {
      loading: false,
      operationList: [],
      nextList: [],
      isShareSetting: false
    };
  },
  beforeCreate() {
    window.revocationFlag = false;
  },
  destroyed() {
    this.operationList = [];
    this.nextList = [];
  },
  mounted: function() {
    var that = this;
    /*var fn=function(e) {
      if (90 == e.keyCode && e.ctrlKey)
      {
        that.revocation()

      }
      if(88 == e.keyCode && e.ctrlKey){
        that.recover()
      }
    }
    document.removeEventListener("keydown",fn)
    document.addEventListener("keydown",fn)*/
  },
  computed: {
    obj: function() {
      return JSON.stringify(this.$store.state.editor.editorPage);
    },
    operationFlag: function() {
      return this.$store.state.user.operationFlag;
    }
  },
  watch: {
    obj: function(v) {
      var that = this;
      if (!revocationFlag) {
        if (that.operationList.length == 0) {
          that.operationList.push(v);
        }
        return;
      }
      window.hasSaveFlag = false;
      clearTimeout(time);
      time = setTimeout(function() {
        if (that.operationFlag) {
          that.nextList = [];
          that.operationList.push(v);
        }
      }, 500);
    }
  },
  methods: {
    editTitle() {
      console.log("编辑标题");
      this.$prompt("请输入测试标题", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: "测试标题不为空",
        inputValue: this.title
      })
        .then(({ value }) => {
          let param = {
            id: this.shareModel.id,
            title: value,
            updator: "admin"
          };
          api.saveTheme(param).then(res => {
            if (res.success) {
              this.$message.success("保存成功");
              this.title = value;
            } else {
              this.$message.error("数据加载失败,请重试");
            }
          });
        })
        .catch(() => {});
    },
    notempty(arrays) {
      for (var i = 0; i < arrays.length; i++) {
        if (
          arrays[i] == "" ||
          arrays[i] == null ||
          typeof arrays[i] == "undefined"
        ) {
          arrays.splice(i, 1);
          i--;
        } else {
          this.$store.dispatch("addElement", arrays[i]);
        }
      }
      return arrays;
    },
    uploadFn(e) {
      var that = this;
      var form = document.getElementById("upload"),
        formData = new FormData(form);
      document.getElementById("itemId").innerText = this.$route.query.itemId;
      // this.$store.dispatch('uploadPsd', formData)
      const loading = this.$loading({
        lock: true,
        text: "psd解析中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        api
          .uploadPsd(formData)
          .then(function(res) {
            loading.close();
            var res = res;
            that.$store.state.editor.editorPage.elements = [];
            that.notempty(res["pages"][0].elements);
            // that.$store.state.editor.editorPage.elements=res['pages'][0].elements
            that.$store.state.editor.editorTheme.title = res["title"];
            that.$store.state.editor.editorTheme.description =
              res["description"];
            that.$store.state.editor.editorTheme.canvasHeight = Number(
              res["canvasHeight"]
            );
            that.$store.state.editor.editorTheme.canvasWidth =
              res["canvasWidth"];
          })
          .catch(function(err) {
            loading.close();
            that.$message.error("psd文件解析失败");
          });
      } catch (e) {
        loading.close();
        that.$message.error("psd文件解析失败");
      }
      form.reset();
    },
    revocation() {
      if (this.operationList.length < 2) {
        return false;
      }
      if (!revocationFlag) {
        return false;
      }
      revocationFlag = false;
      var str = this.operationList.splice(this.operationList.length - 1, 1);
      this.nextList.push(str[0]);
      this.$store.state.editor.editorPage.elements = JSON.parse(
        this.operationList[this.operationList.length - 1]
      ).elements;
      setTimeout(function() {
        revocationFlag = true;
      }, 400);
    }, //撤销
    recover() {
      if (this.nextList.length == 0) {
        return false;
      }
      if (!revocationFlag) {
        return false;
      }
      revocationFlag = false;
      this.$store.state.editor.editorPage.elements = JSON.parse(
        this.nextList[this.nextList.length - 1]
      ).elements;
      this.operationList.push(
        this.nextList.splice(this.nextList.length - 1, 1)[0]
      );
      setTimeout(function() {
        revocationFlag = true;
      }, 400);
    }, //恢复
    deploy() {
      // this.loading = true
      /*this.$store.dispatch('saveTheme', tools.vue2json(this.$store.state.editor.editorTheme)).then(() => {
        // setTimeout(() => {
        //   this.$emit('saveThemeSuccess')
        //   this.loading = false
        // }, 1000)
        this.$emit('saveThemeSuccess')
        this.loading = false
      })*/

      if (!window.hasSaveFlag) {
        this.$confirm("您确定不保存直接预览吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            window.hasSaveFlag = false;
            this.$emit("saveThemeSuccess");
          })
          .catch(() => {});
      } else {
        this.$emit("saveThemeSuccess");
      }
    },
    grid() {
      //网格
      if (!this.$store.state.editor.gridTempField) {
        this.$store.state.editor.gridTempField = true;
      } else {
        this.$store.state.editor.gridTempField = false;
      }
    },
    psd() {
      var that = this;
      axios.get("../../static/json.json").then(function(res) {
        var res = res.data;
        that.$store.state.editor.editorTheme.title = res["title"];
        that.$store.state.editor.editorTheme.description = res["description"];
        that.$store.state.editor.editorTheme.canvasHeight = res["canvasHeight"];
        that.$store.state.editor.editorTheme.canvasWidth = res["canvasWidth"];
        that.$store.state.editor.editorPage.elements = res["pages"][0].elements;
      });
    },
    shareSetting() {
      this.isShareSetting = true;
    },
    closeShare() {
      this.isShareSetting = false;
    }
  }
};
</script>

<style lang="less" scoped>
.header {
  height: 60px;
  background-color: #fff;
  color: #646b81;
  margin-top: 60px;
  position: relative;
  display: flex;
  flex-direction: row;
  .reset-btn {
    position: absolute;
    left: 0px;
    top: 0px;
    height: 100%;
    padding: 0 50px;
    cursor: pointer;
    display: flex;
    flex-direction: row;
    align-items: center;
    max-width: 30%;
    .reset-title {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .el-icon-arrow-left {
    margin-right: 10px;
  }
  .right-panel {
    float: right;
    height: 100%;
    width: 100px;
    display: flex;
    align-items: center;
    padding-right: 15px;
    flex-direction: row-reverse;
  }
  .edit-title {
    padding-left: 10px;
  }
  .tools {
    width: 100%;
    height: 60px;
    .next_return {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      height: 100%;
      .return {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding-left: 16px;
        padding-right: 16px;
        font-size: 16px;
        color: rgba(100, 107, 129, 1);
        .retutn_icon {
          width: 17px;
          height: 14px;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>
