<template>
  <header class="header">
    <button class="reset-btn"
            @click="goback"><i class="el-icon-arrow-left"></i>返回作品</button>
    <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>
  </header>
</template>

<script>
import tools from '../util/tools'
import api from '../api/editor'
var time=null
export default {
  props: {
    goback: Function
  },
  data () {
    return {
      loading: false,
      operationList:[],
      nextList:[]
    }
  },
  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: {
    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
      })
    }
  }
}
</script>

<style lang="less" scoped>
.header {
  height: 60px;
  background-color: #373f42;
  color: #fff;
  .reset-btn {
    height: 100%;
    padding: 0 20px;
    cursor: pointer;
  }
  .el-icon-arrow-left {
    margin-right: 20px;
  }
  .right-panel {
    float: right;
    height: 100%;
    width: 100px;
    display: flex;
    align-items: center;
    padding-right: 15px;
    flex-direction: row-reverse;
  }
  .next_return{
    display: inline-block;
    margin-left: 33%;
    span{
      display: inline-block;
      width: 30px;
      height: 24px;

    }
    .return{
      background: url("../../static/img/button_return.png") no-repeat center center /100% 100%;
    }
    .next{
      margin-left: 50px;
      background: url("../../static/img/button_next.png") no-repeat center center /100% 100%;
    }
  }
}
</style>
