<template>
  <div style="height: 100%;">
    <el-row style="height: 100%;">
      <el-col :span="16">
        <div id="blocklyDiv" style="height: 100%; width: 100%;"></div>
      </el-col>
      <el-col :span="8">
        <div style="height: 100%;">
          <div style="height: calc(100vh - 350px);overflow-y: auto;">
            <codeHeader @getSwitchs="getSwitch" @getCodemirror="getCodemirror" @getPythonCode="getChildrenPythonCode" />
            <codeMirrorPython :pythonCode="pythonCode" v-if="codeShow" :codeMirrorShow="CodemirrorShow" />
            <Serialoutput v-else />
          </div>
          <div style="height: 230px;">
            <Device />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref, onMounted, shallowRef, watchEffect, onUpdated } from "vue"
import Blockly from 'blockly';
// import { pythonGenerator } from "blockly/python";
import hans from '../blockly/msg/zh-hans';
import hant from '../blockly/msg/zh-hant';
import en from '../blockly/msg/en';
import blocklyXml from '../blockly/blocklyXml'
import Basic from '@/blockly/blocks/index'
import BlocklyStyle from '../blockly/style/blockly'
import BlocklyPython from '../blockly/pythonCode/index'
import codeMirrorPython from './codemirror/codemirror.vue'
import store from '../stores/blockly'
import Device from './device/device.vue'
import codeHeader from './codemirror/header.vue'
import Serialoutput from "./codemirror/Serialoutput.vue";

const workspace = shallowRef(null)
const pythonCode = ref('')
const CodemirrorShow = ref(true)
const xmlStr = store.useyXmlStore()
const storePythonCode = store.useyPythonCodeStore()
const LoadBlocklyStatus = store.useLoadBlocklyStatus()
const codeShow = ref(true)
const language = ref(null)

onMounted(() => {
  let lang = hans
  if (localStorage.getItem('lang') == 'en') {
    lang = en
  } else if (localStorage.getItem('lang') == 'zhHant') {
    lang = hant
  }
  language.value = lang
  let blocklyXmls = Blockly.utils.xml.textToDom(blocklyXml.xml)
  var categoryNodes = blocklyXmls.getElementsByTagName('category');
  for (var i = 0, cat; cat = categoryNodes[i]; i++) {
    var catId = cat.getAttribute('id');
    var catText = language.value[catId] || catId;
    if (catText) {
      cat.setAttribute('name', catText);
    }
  }
  // blockly 初始化
  initBlockly(blocklyXmls)
  // 加载 blockly 积木样式
  // 判断localStorage是否有积木保存
  if (localStorage.getItem('workspaceXml')) {
    // 加载本地存储保存的积木
    getLocalStorageXml();
  }
})
// 
const getSwitch = (val) => {
  codeShow.value = val
  pythonCode.value = storePythonCode.pythonCode
}
const getCodemirror = (val) => {
  CodemirrorShow.value = !val
}
const getChildrenPythonCode = val => {
  pythonCode.value = val
}
const initBlockly = (xml) => {
  Blockly.Blocks = Basic.Blocks
  Blockly.Python = BlocklyPython.Python
  Blockly.setLocale(language.value);
  workspace.value = Blockly.inject('blocklyDiv', {
    toolbox: xml,
    theme: BlocklyStyle,
    collapse: true,
    comments: true,
    css: true,
    disable: true,
    grid: false,
    maxBlocks: Infinity,
    rtl: false,
    scrollbars: true,
    sounds: true,
    trashcan: true,
    zoom: {
      controls: true,
      wheel: false,
      startScale: 1.0,
      maxScale: 2,
      minScale: 0.2,
      scaleSpeed: 1.2
    }
  });
  // 添加事件监听器
  workspace.value.addChangeListener(addBlocklyEventListeners)
  console.log('blockly init success', workspace.value);
  window.blockly = workspace.value
  window.Blockly = Blockly
}
const addBlocklyEventListeners = (event) => {
  if (event.type == Blockly.Events.BLOCK_DRAG || event.type == "viewport_change") {
    // 在块被拖动时执行的逻辑
    getWorkspaceXml()
  }
  // 积木区域操作是生成代码
  getPythonCode()
}
const getPythonCode = () => {
  let code = Blockly.Python.workspaceToCode(workspace.value);
  var xml = Blockly.Xml.domToText(Blockly.Xml.workspaceToDom(workspace.value))
  // console.log('--------Python code-------');
  pythonCode.value = code
  storePythonCode.$patch({ pythonCode: code })
  xmlStr.$patch({ xmlStr: xml })
}
const getWorkspaceXml = () => {
  var xml = Blockly.Xml.domToText(Blockly.Xml.workspaceToDom(workspace.value))
  localStorage.setItem('workspaceXml', xml)
  // console.log('--------workspace xml-------');
  // console.log(xml);
  // console.log('当前工作区 xml 已保存到 localStorage 中...');
}
const getLocalStorageXml = () => {
  let xml = localStorage.getItem('workspaceXml');
  if (xml) {
    Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(xml), workspace.value)
  }
}

watchEffect(() => {
  // console.log(LoadBlocklyStatus.status)
  if (LoadBlocklyStatus.status) {
    workspace.value.clear()
    Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(xmlStr.xmlStr), workspace.value)
  }
})
</script>

<style scoped>
#blocklyDiv {
  height: 100%;
  width: 100%;
  text-align: left;
}
</style>
