<template>
  <div class="ablockly">
    <div class="btnPosition">
      <el-button type="primary" @click="go">下一步</el-button>
      <el-button type="primary" @click="returnA">上一步</el-button>
    </div>
    <div id="blocklyDiv"></div>
    <xml id="toolbox" style="display: none">
      <category name="逻辑" colour="%{BKY_LOGIC_HUE}">
        <block type="controls_if"></block>
        <block type="logic_compare"></block>
        <block type="logic_operation"></block>
        <block type="logic_negate"></block>
        <block type="logic_boolean"></block>
        <block type="logic_number"></block>
      </category>
      <sep></sep>
      <category name="循环" colour="#5ba55b">
        <block type="controls_repeat_forever"></block>
        <block type="controls_whileUntil"></block>
        <block type="controls_for"></block>
      </category>
      <sep></sep>
      <category id="catIOTScreen" name="屏幕" colour="#5cb2d6">
        <block type="iot_lcd_screeninit"></block>
      </category>
      <sep></sep>
      <category id="cat" name="人脸识别" colour="#ee783a">
        <block type="iot_lcd_faceinit"></block>
        <block type="iot_lcd_objectinit"></block>
      </category>
      <sep></sep>
      <category id="police" name="识别组件" colour="#1b5873">
        <block type="iot_lcd_policeinit"></block>
        <block type="police_objectinit"></block>
      </category>
      <sep></sep>
      <category id="voice" name="语音组件" colour="#9200ff">
        <block type="voice_voiceinit"></block>
        <block type="voice_talk"></block>
        <block type="voice_open"></block>
      </category>
      <sep></sep>
      <category id="ai" name="AI组件" colour="#935ba5">
        <block type="ai_gesture"></block>
        <block type="ai_motor"></block>
      </category>
      <sep></sep>
      <category id="light" name="灯光" colour="#3a8ee6">
        <block type="light_open"></block>
        <block type="light_close"></block>
      </category>
      <sep></sep>
      <category id="curtain" name="窗帘" colour="#26DDFF">
        <block type="curtain_open"></block>
        <block type="curtain_close"></block>
      </category>
    </xml>
  </div>
</template>


<style scoped>
.ablockly,
#blocklyDiv {
  width: 100%;
  height: 100%;
}

.blocklySvg {
  height: 905px !important;
}

.btnPosition {
  position: fixed;
  right: 130px;
  bottom: 35px;
  z-index: 999999;
}
</style>


<script>
// 引入Blockly
import Blockly from "blockly";
// 引入想要转换的语言，语言有php python dart lua javascript
import * as JavaScript from "blockly/javascript";
import * as Blocks from "blockly/blocks";
// 引入语言包并使用
import * as hans from "blockly/msg/zh-hans";
Blockly.setLocale(hans);
//引入媒体文件：我是在github上下载的blockly源码，将源码中的media文件放入我项目中的public文件夹下

//忽略被vue错认为组件的blockly中的标签，不止以下这些，请发现一个忽略一个
import Vue from "vue";
Vue.config.ignoredElements.push("xml");
Vue.config.ignoredElements.push("block");
Vue.config.ignoredElements.push("field");
Vue.config.ignoredElements.push("category");
Vue.config.ignoredElements.push("sep");
Vue.config.ignoredElements.push("value");
Vue.config.ignoredElements.push("statement");
Vue.config.ignoredElements.push("mutation");

export default {
  data() {
    return {
      that: this,
      workspace: null,
      type: this.$route.query.typeN,
    };
  },

  methods: {
    // 代码生成器
    myUpdateFunction(event) {
      var code = Blockly.JavaScript.workspaceToCode(this.workspace);
      // debugger;
      return code;
    },
    // 获取blockly工作区中的code和xml结构
    getBlockData() {
      const code = Blockly.JavaScript.workspaceToCode(this.workspace);
      const xml = Blockly.Xml.workspaceToDom(this.workspace);
      const xmlText = Blockly.Xml.domToText(xml);
    },
    // 回显工作区中的xml结构
    setBlockData(xmlText) {
      this.clearBlockData();
      const xml = Blockly.Xml.textToDom(xmlText);
      Blockly.Xml.domToWorkspace(xml, this.workspace);
    },
    // 清空工作区
    clearBlockData() {
      this.workspace.clear();
    },
    //下一步
    go() {
      //       var xmlText =
      //   '<xml xmlns="https://developers.google.com/blockly/xml"><block type="iot_lcd_screeninit" id="{3nwI]%M1OB@v~%c^GJ*" x="270" y="150"><next><block type="controls_repeat_forever" id="%RwQN-vn~S,Qz:U%Dp2C"><statement name="DO"><block type="controls_if" id="tTNBMMPITBf)yE@hA}Lt"><value name="IF0"><block type="logic_compare" id="kW(af5I*_dMR|37aEHA8"><field name="OP">EQ</field><value name="A"><block type="ai_gesture" id="Msy)DT1[/[pA7vU$u2BD"><field name="ID">ID</field></block></value><value name="B"><block type="logic_number" id="F7nQ+Rn{h=Z-:`nxfOV{"><field name="number">布</field></block></value></block></value><statement name="DO0"><block type="ai_motor" id="9=+m`N)^mOs;,8?7ZZ:K"><field name="motor">M1</field><field name="speed">100</field></block></statement><next><block type="controls_if" id="~ykQvxBR]wnz6FHIGc^s"><value name="IF0"><block type="logic_compare" id="+v0*1:oG$.+wMFe_g_F@"><field name="OP">EQ</field><value name="A"><block type="ai_gesture" id=",|{9@1In%8:74vXPPn{O"><field name="ID">ID</field></block></value><value name="B"><block type="logic_number" id="[J4:1z-D*iz3){K$v[gM"><field name="number">石头</field></block></value></block></value><statement name="DO0"><block type="ai_motor" id="XIVuWHcKb[O5|0*HC_Em"><field name="motor">M1</field><field name="speed">0</field></block></statement><next><block type="controls_if" id="bNZCd.Zj2arimcA^dZvc"><value name="IF0"><block type="logic_compare" id="ul/^s*@P{HkWe6(^9fgn"><field name="OP">EQ</field><value name="A"><block type="ai_gesture" id="Wd)15h0yyFb`)Sy:H}0w"><field name="ID">ID</field></block></value><value name="B"><block type="logic_number" id="1f0Wep9dlC0i-})rTiqN"><field name="number">剪刀</field></block></value></block></value><statement name="DO0"><block type="ai_motor" id="bY;.J)_PvmP5TAD/KDs,"><field name="motor">M1</field><field name="speed">50</field></block></statement></block></next></block></next></block></statement></block></next></block></xml>';
      // this.setBlockData(xmlText);
      //update修改   function state里的参数
      var a = this.myUpdateFunction();
      this.$store.commit("update", ["function", a]);
      console.log(a);
      if (this.type == "fan") {
        this.$router.push("Ffun");
      } else if (this.type == "light") {
        this.$router.push("Flight");
      } else if (this.type == "curtain") {
        this.$router.push("Fcurtain");
      } else if (this.type == "shop") {
        this.$router.push("Fshop");
      } else {
        this.$router.push("function");
      }
    },
    returnA() {
      this.$router.go(-1);
    },
  },

  mounted() {
    this.workspace = Blockly.inject("blocklyDiv", {
      //工具栏
      toolbox: document.getElementById("toolbox"),
      //网格效果
      grid: { spacing: 20, length: 3, colour: "#ccc", snap: true },
      //媒体资源
      media: "../assets/img/",
      //垃圾桶
      trashcan: true,
    });
    //工作区监听代码生成器
    this.workspace.addChangeListener(this.myUpdateFunction);

    Blockly.Blocks["iot_lcd_screeninit"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldImage(
            require("../assets/img/screen_init_header.png"),
            45,
            45
          )
        );
        this.appendDummyInput().appendField("LCD屏幕打开");
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#5cb2d6");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };

    Blockly.JavaScript.iot_lcd_screeninit = function (block) {
      var _code = "screen=1;";
      return _code;
    };

    Blockly.Blocks["iot_lcd_faceinit"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldImage(
            require("../assets/img/face_recognition_header.png"),
            45,
            45
          )
        );
        this.appendDummyInput().appendField("人脸辨识");
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#ee783a");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };

    Blockly.JavaScript.iot_lcd_faceinit = function (block) {
      var _code = "face=1;";
      return _code;
    };

    Blockly.Blocks["iot_lcd_policeinit"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldImage(
            require("../assets/img/screen_init_header.png"),
            45,
            45
          )
        );
        this.appendDummyInput().appendField("电子警察组件");
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#1b5873");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };

    Blockly.JavaScript.iot_lcd_policeinit = function (block) {
      var _code = "police=1;";
      return _code;
    };

    Blockly.Blocks["police_objectinit"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldImage(
            require("../assets/img/screen_init_header.png"),
            45,
            45
          )
        );
        this.appendDummyInput().appendField("物体识别对比组件");
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#1b5873");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };

    Blockly.JavaScript.police_objectinit = function (block) {
      var _code = "pObject=1;";
      return _code;
    };

    Blockly.Blocks["logic_loop"] = {
      init: function () {
        this.appendStatementInput("NAME")
          .setCheck(null)
          .appendField("重复执行");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#5b80a5");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["logic_loop"] = function (block) {
      var statements_name = Blockly.JavaScript.statementToCode(block, "NAME");
      // TODO: Assemble JavaScript into code variable.
      var code = "for;\n";
      return code;
    };

    Blockly.Blocks.controls_repeat_forever = {
      init: function () {
        this.jsonInit({
          message0: Blockly.Msg.CONTROLS_REPEAT_FOREVER,
          previousStatement: null,
          nextStatement: null,
          colour: "#5ba55b",
          tooltip: Blockly.Msg.CONTROLS_REPEAT_FOREVER_TOOLTIP,
          helpUrl: Blockly.Msg.CONTROLS_REPEAT_HELPURL,
        });
        this.appendStatementInput("DO").appendField(
          Blockly.Msg.CONTROLS_REPEAT_INPUT_DO
        );
      },
    };

    Blockly.JavaScript.controls_repeat_forever = function (a) {
      var d = Blockly.JavaScript.statementToCode(a, "DO");
      d = Blockly.JavaScript.addLoopTrap(d, a);
      return "while (true) {\n" + d + "}\n";
    };

    Blockly.Blocks["logic_number"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldTextInput("0"),
          "number"
        );
        this.setInputsInline(true);
        this.setOutput(true, "Number");
        this.setColour("#5b80a5");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["logic_number"] = function (block) {
      var text_number = block.getFieldValue("number");
      // TODO: Assemble JavaScript into code variable.
      var code = text_number;
      // TODO: Change ORDER_NONE to the correct strength.
      return [code, Blockly.JavaScript.ORDER_NONE];
    };
    Blockly.Blocks["ai_gesture"] = {
      init: function () {
        this.appendDummyInput()
          .appendField("AI手势识别")
          .appendField(new Blockly.FieldDropdown([["ID", "ID"]]), "ID");
        this.setInputsInline(true);
        this.setOutput(true, null);
        this.setColour(285);
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["ai_gesture"] = function (block) {
      var dropdown_id = block.getFieldValue("ID");
      // TODO: Assemble JavaScript into code variable.
      var code = "hands";
      // TODO: Change ORDER_NONE to the correct strength.
      return [code, Blockly.JavaScript.ORDER_NONE];
    };
    Blockly.Blocks["ai_motor"] = {
      init: function () {
        this.appendDummyInput()
          .appendField("马达")
          .appendField(new Blockly.FieldDropdown([["M1", "M1"]]), "motor")
          .appendField("以速度")
          .appendField(new Blockly.FieldTextInput("0"), "speed")
          .appendField("转动");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(285);
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["ai_motor"] = function (block) {
      var dropdown_motor = block.getFieldValue("motor");
      var text_speed = block.getFieldValue("speed");
      // TODO: Assemble JavaScript into code variable.
      var code = "motor=" + text_speed;
      // TODO: Change ORDER_NONE to the correct strength.
      return code;
    };

    Blockly.Blocks["iot_lcd_objectinit"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldImage(
            require("../assets/img/face_recognition_header.png"),
            45,
            45
          )
        );
        this.appendDummyInput().appendField("物体辨识");
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#ee783a");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };

    Blockly.JavaScript.iot_lcd_objectinit = function (block) {
      var _code = "object=1";
      return _code;
    };

    Blockly.Blocks["voice_voiceinit"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldImage(
            require("../assets/img/screen_init_header.png"),
            45,
            45
          )
        );
        this.appendDummyInput().appendField("语音识别");
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#9200ff");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };

    Blockly.JavaScript.voice_voiceinit = function (block) {
      var _code = "voice=1;";
      return _code;
    };

    Blockly.Blocks["voice_open"] = {
      init: function () {
        this.appendDummyInput().appendField(
          new Blockly.FieldImage(
            require("../assets/img/screen_init_header.png"),
            45,
            45
          )
        );
        this.appendDummyInput().appendField("打开音频");
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#9200ff");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };

    Blockly.JavaScript.voice_open = function (block) {
      var _code = "voiceOpen=1;";
      return _code;
    };

    Blockly.Blocks["voice_talk"] = {
      init: function () {
        this.appendDummyInput()
          .appendField("说出")
          .appendField(new Blockly.FieldTextInput(""), "say");
        this.setOutput(true, null);
        this.setColour("#9200ff");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["voice_talk"] = function (block) {
      var text_say = block.getFieldValue("say");
      var code = "say="+text_say;
      // return code;
      return [code, Blockly.JavaScript.ORDER_NONE];
    };
    Blockly.Blocks["light_open"] = {
      init: function () {
        this.appendDummyInput().appendField("打开灯光");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#3a8ee6");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["light_open"] = function (block) {
      // TODO: Assemble JavaScript into code variable.
      var code = "light=1";
      return code;
    };
    Blockly.Blocks["light_close"] = {
      init: function () {
        this.appendDummyInput().appendField("关闭灯光");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#3a8ee6");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["light_close"] = function (block) {
      // TODO: Assemble JavaScript into code variable.
      var code = "light=0";
      return code;
    };
    Blockly.Blocks["curtain_open"] = {
      init: function () {
        this.appendDummyInput().appendField("打开窗帘");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#26DDFF");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["curtain_open"] = function (block) {
      // TODO: Assemble JavaScript into code variable.
      var code = "curtain=1";
      return code;
    };
    Blockly.Blocks["curtain_close"] = {
      init: function () {
        this.appendDummyInput().appendField("关闭窗帘");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#26DDFF");
        this.setTooltip("");
        this.setHelpUrl("");
      },
    };
    Blockly.JavaScript["curtain_close"] = function (block) {
      // TODO: Assemble JavaScript into code variable.
      var code = "curtain=0";
      return code;
    };
  },
};
</script>