<template>
  <div class="mainpage">
    <el-container>
      <el-header>
        <Header v-if="canvas" :canvasdata="canvas.data" @onMessage="onMessage" @onMenu="onMenu" />
      </el-header>
      <el-main id="content" style="overflow: hidden">
        <el-collapse-transition>
          <div>
            <!--v-show="show3"-->
            <div id="left">
              <Pens />
            </div>
          </div>
        </el-collapse-transition>
        <div id="middle">
          <div id="rootElement" ref="rootElement" class="full"></div>
          <!-- <i
            style="position: fixed;top: 50%;color:blue"
            :class="show3?'el-icon-d-arrow-left':'el-icon-d-arrow-right'"
            @click="show3 = !show3"
          ></i>
         
          <svg
            v-show="canvasGrid=='true'"            
            width="100%"
            height="100%"
            xmlns="http://www.w3.org/2000/svg"
          >
            <defs>
              <pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse">
                <path d="M 10 0 L 0 0 0 10" fill="none" stroke="#f3f3f3" stroke-width="1" />
              </pattern>
            </defs>
            <rect width="100%" height="100%" fill="url(#grid)" />
          </svg>
          -->
        </div>
        <div id="right">
          <Filepropertys v-if="!isSelected" @onMessage="onMessage" :canvas="canvas" :page="page" />
          <Nodepropertys v-if="isSelected" @onMessage="onMessage" :canvas="canvas" :nodes="nodes" />
        </div>
      </el-main>
    </el-container>
  </div>
</template>


<style>
a:hover {
  color: #1bb5f5;
}
i {
  font-size: 35px;
}

.mainpage {
  width: 100vw;
  height: 100vh;
  position: fixed;
}

.el-container {
  height: 100%;
}
.el-header {
  background-color: #545c64;
  text-align: center;
}
.el-main {
  flex: 1;
  padding: 0px !important;
}

.full {
  height: 100%;
  flex: 1;
  border: 1px solid #000;
}

#content {
  display: flex;
  width: 100%;
  height: 200px;
}
#left {
  flex: 0 0 220px;
  height: 100%;
  width: 246px;
  overflow-y: auto;
}
#middle {
  flex: 1;
}
#right {
  height: 100%;
  width: 246px;
  overflow-y: auto;
}


</style>
<script>

import { Topology, Lock, Options, Pen } from '@topology/core'
import * as FileSaver from 'file-saver'
import { Store } from 'le5le-store'
import Header from "@/components/head"//"/components/head.vue"
import Nodepropertys from "@/components/nodepropertys"
import Filepropertys from "@/components/filepropertys"
import Pens from "@/components/pens.vue"
import store from '@/store/index'

import "@/assets/js/canvas2svg"

export default {
  components: {
    Header, Pens, Nodepropertys, Filepropertys
  },
  data()
  {
    return {
      //show3: true,
      canvas: null,
      canvasGrid: false,
      canvasOptions: {
        rotateCursor: '/img/rotate.cur',
        color: this.$store.state.designsetting.elementColor,
        font: {
          color: this.$store.state.designsetting.elementColor,
        }
      },
      contextmenu: {},
      editFilename: false,
      page: {
        path: "/",
        name: "",
        elementColor: this.$store.state.designsetting.elementColor,
        paintColor: this.$store.state.designsetting.paintColor,
      },
      nodes: {
        pen: {},
        pens: []
      },
      isSelected: false,
      cpPresetColors: [
        '#1890ff',
        '#096dd9',
        '#bae7ff',
        '#52c41a',
        '#3fad09',
        '#c6ebb4',
        '#faad14',
        '#d9a116',
        '#fff6dd',
        '#f50000',
        '#ff0000',
        '#ffc2c5',
        '#fa541c',
        '#531dab',
        '#314659',
        '#777777'
      ],
    }
  },

  created()
  {
    // if (process.client && window['echartsData']) {
    //   for (let key in window['echartsData']) {
    //     document.body.removeChild(window['echartsData'][key]).div
    //   }
    //   window['echartsData'] = {}
    // }
    //canvasRegister();
    // if (process.client) {
    //   document.onclick = event =>
    //   {
    //     this.contextmenu = {
    //       left: null,
    //       top: null,
    //       bottom: null
    //     }
    //   }
    // }
  },
  mounted()
  {
    this.init();
  },
  computed: {
    event()
    {
      return this.$store.state.event.event
    }
  },
  watch: {
    // event(curVal)
    // {
    //   console.log("_________________________________________________!@!!!!!!!!!!!!!!!__________")
    //   console.log(curVal);
    //   if (this[curVal.name]) {
    //     this[curVal.name](curVal.data)
    //   }
    // },
    // $route(val)
    // {
    //   this.open()
    // }
  },
  methods: {
    init()
    {
      window.scrollTo(0, 0);
      this.canvasOptions.on = this.onMessage;
      this.canvas = new Topology('rootElement', this.canvasOptions);
      this.canvasHeight = this.canvas.canvas.height;
      this.$store.state.canvas = this.canvas;
      window.v = this.canvas;
      window.s = this.$store;
    },
    async open()
    {
      if (!this.$route.query.id) {
        return
      }

      if (data && data.id) {
        canvas.open(data.data)
      }
    },
    onMenu(docmd, value)
    {
      console.log(docmd)
      console.log(value)
      switch (docmd) {
        case "new":
          { this.OnNew(); } break;
        case "open":
          {
            this.OnNew();
            this.OnOpen();
            /**

            0 /预处理
            1 /预处理/监视页面/蒸发塔.json
            2 /加料/测试页面.json
            3 /主页面.json

             */
          } break;
        case "save":
          {
            /*
            此处页面保存到服务端
            文件名称:(前后端做好防注入准备,只允许输入中英文数字和转义的反斜杠)
            然后界面需要提供一个树形结构或者列表,方便用户操作(路劲添加或者路劲选择)
            */
            this.OnSave();
          } break;
        case "donwloadJson":
          { this.OnSave(); } break;
        case "donwloadPNG":
          { this.OnSavePng(); } break;
        case "donwloadSVG":
          { this.OnSaveSvg(); } break;
        case "undo":
          { this.OnUndo(); } break;
        case "redo":
          { this.OnRedo(); } break;
        case "cut":
          { this.OnCut(); } break;
        case "copy":
          { this.OnCopy(); } break;
        case "paste":
          { this.OnPaste(); } break;
        case "scale":
          { this.canvas.scaleTo(value); }
          break;
        case "lock":
          { this.OnLock(value); } break;
      }

    },
    // 右侧输入框编辑状态时点击编辑区域其他元素，onMessage执行后才执行onUpdateProps方法，通过setTimeout让onUpdateProps先执行
    onMessage(event, value)
    {
      setTimeout(() =>
      {
        switch (event) {
          case 'node':
          case 'addNode':
          case 'line':
          case 'addLine':
            {
              this.nodes = {
                pen: value
              };
              this.isSelected = true;
              this.locked = value.locked;
            }
            break;
          case 'multi':
            {
              this.locked = true;
              if (value && value.length) {
                this.nodes = {
                  pens: value
                };
                this.isSelected = true;
                for (const item of value) {
                  if (!item.locked) {
                    this.locked = false;
                    break;
                  }
                }
              }
            }
            break;
          case 'space':
            {
              this.nodes = {
                pen: {},
                pens: []
              }
              this.isSelected = false;
            }
            break;
          case 'moveOut':
            {
              this.$refs.rootElement.scrollLeft += 10;
              this.$refs.rootElement.scrollTop += 10;
            }
            break;
          case 'resize':
            {
              if (value) {
                this.canvasHeight = value.height;
              }
            }
            break;
          case 'locked':
            {
              Store.set('locked', value);
              break;
            }
          case "refresh":
            {
              this.canvas.render();
            } break;
          case "setElementColor":
            {
              if (this.canvasOptions) {
                this.canvasOptions.color = value;
                this.canvasOptions.font.color = value;
              }

              if (this.canvas && this.canvas.options) {
                this.canvas.options.color = value;
                this.canvas.options.font.color = value;
              }
            } break;
          case "showGrid":
            {
              if (this.canvas.data) {
                this.canvas.data.grid = value;
                this.canvasGrid = value;
              }
            } break;
          default:
            {
              console.log('onMessage_____Default:', event, value);
            } break;
        }
        console.log('onMessage:', event, value);
      }, 50)

      window.n = this.nodes;
    },
    /***
    @param lockNumber {number} 0,1,2(可选)      0:解除lock, 1:可选中不可拖动 2:不可选中 */
    OnLock(lockNumber)
    {
      this.canvas.lock(lockNumber);
      // if (data.nodes && data.nodes.length) {
      //   for (const item of data.nodes) {
      //     if (!item.locked) {
      //       locked = false
      //       break
      //     }
      //   }
      // }
    },

    onUpdateProps(node)
    {
      console.log("canvas.updateProps(node)");
      // 如果是node属性改变，需要传入node，重新计算node相关属性值
      // 如果是line属性改变，无需传参
      canvas.updateProps(node)
    },

    OnNew(data)
    {
      this.canvas.open();
      this.canvas.data.lineName = this.$store.state.designsetting.lineStyleName;
      this.canvas.data.fromArrowType = this.$store.state.designsetting.fromArrowType;
      this.canvas.data.toArrowType = this.$store.state.designsetting.toArrowType;
      this.canvas.data.bkColor = this.$store.state.designsetting.paintColor;
      this.canvas.render();
      this.canvas.scaleTo(1);
    },

    OnOpen(data)
    {
      this.OnReplace(data)
    },
    OnReplace()
    {
      const input = document.createElement('input')
      input.type = 'file'
      input.onchange = event =>
      {
        const elem = event.target;
        if (elem.files && elem.files[0]) {
          if (elem.files[0].name.indexOf('.json') > 0) {
            this.OpenJson(elem.files[0]);
          } else {
            //this.openZip(elem.files[0]);
          }
        }
      }
      input.click()
    },
    OpenJson(file)
    {
      const name = file.name.replace('.json', '');
      const reader = new FileReader();
      reader.onload = (e) =>
      {
        const text = e.target.result + '';
        try {
          const data = JSON.parse(text);
          data.lineName = this.$store.state.designsetting.lineStyleName;
          data.fromArrowType = this.$store.state.designsetting.fromArrowType;
          data.toArrowType = this.$store.state.designsetting.toArrowType;
          data.name = name;
          //data.scale = 1;

          if (data.bkColor) {
            this.$store.dispatch('setCanvasBackColor', data.bkColor);
          }
          this.canvas.open(data);
          this.canvas.scaleTo(1);
          this.canvas.data.bkColor = data.bkColor;
          this.$store.dispatch('setCanvas', this.canvas);
        } catch (e) {
          //console.log(e)
        }
      };
      reader.readAsText(file);
    },
    OnSave(data)
    {
      FileSaver.saveAs(
        new Blob([JSON.stringify(this.canvas.data)], {
          type: 'text/plain;charset=utf-8'
        }),
        `X.json`
      )
    },
    OnSavePng(data)
    {
      this.canvas.saveAsImage('GyeeX.png')
    },
    OnSaveSvg(data)
    {
      const ctx = new C2S(this.canvas.canvas.width + 200, this.canvas.canvas.height + 200)
      for (const item of this.canvas.data.pens) {
        item.render(ctx)
      }
      let mySerializedSVG = ctx.getSerializedSvg()
      mySerializedSVG = mySerializedSVG.replace(
        '<defs/>',
        `<defs>
          <style type="text/css">
            @font-face {
              font-family: 'topology';
              src: url('http://at.alicdn.com/t/font_1331132_h688rvffmbc.ttf?t=1569311680797') format('truetype');
            }
          </style>
        </defs>`
      )

      mySerializedSVG = mySerializedSVG.replace(/--le5le--/g, '&#x')

      const urlObject = window.URL || window
      const export_blob = new Blob([mySerializedSVG])
      const url = urlObject.createObjectURL(export_blob)

      const a = document.createElement('a')
      a.setAttribute('download', 'XGyee.svg')
      a.setAttribute('href', url)
      const evt = document.createEvent('MouseEvents')
      evt.initEvent('click', true, true)
      a.dispatchEvent(evt)
    },
    OnUndo(data)
    {
      this.canvas.undo()
    },
    OnRedo(data)
    {
      this.canvas.redo()
    },
    OnCopy(data)
    {
      this.canvas.copy()
    },
    OnCut(data)
    {
      this.canvas.cut()
    },
    OnPaste(data)
    {
      this.canvas.paste()
    },

    onContextMenu(event)
    {
      event.preventDefault()
      event.stopPropagation()

      if (event.clientY + 360 < document.body.clientHeight) {
        this.contextmenu = {
          left: event.clientX + 'px',
          top: event.clientY + 'px'
        }
      } else {
        this.contextmenu = {
          left: event.clientX + 'px',
          bottom: document.body.clientHeight - event.clientY + 'px'
        }
      }
    },
    destroyed()
    {
      canvas.destroy()
    },
  },

}

</script>

