<!--
 * @Descripttion: 大屏设计器
 !-->
<template>
  <div class="layout">
    <div
      v-if="toolIsShow"
      class="layout-left"
      :style="{ width: widthLeftForTools + 'px' }"
    >
      <el-tabs class="layout-left" type="border-card" :stretch="true">
        <!-- 左侧组件栏-->
        <el-tab-pane label="工具栏">
          <span slot="label"><i class="el-icon-date icon"></i>工具栏</span>
          <div class="chart-type">
            <el-tabs class="type-left" tab-position="left">
              <el-tab-pane
                v-for="(item, index) in widgetTools"
                :key="index"
                :label="item.name"
              >
                <li
                  v-for="(it, idx) in item.list"
                  :key="idx"
                  draggable="true"
                  @dragstart="dragStart(it.code)"
                  @dragend="dragEnd()"
                >
                  <div class="tools-item">
                    <span class="tools-item-icon">
                      <i class="iconfont" :class="it.icon"></i>
                    </span>
                    <span class="tools-item-text">{{ it.label }}</span>
                  </div>
                </li>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-tab-pane>
        <!-- 左侧图层-->
        <el-tab-pane label="图层">
          <draggable
            v-model="layerWidget"
            @update="datadragEnd"
            :options="{ animation: 300 }"
            group="groupA"
          >
            <transition-group>
              <div
                v-for="(item, index) in layerWidget"
                :key="'item' + index"
                class="tools-item"
                :class="widgetIndex == index ? 'is-active' : ''"
                @click="layerClick(index)"
              >
                <span class="tools-item-icon">
                  <i class="iconfont" :class="item.icon"></i>
                </span>
                <span class="tools-item-text">{{ item.label }}</span>
              </div>
            </transition-group>
          </draggable>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 是否显示左侧组件栏-->
    <div class="layout-left-fold"
         :style="{ width: widthLeftForToolsHideButton + 'px' }"
         @click="toolIsShow = !toolIsShow"
    >
      <i :class="[toolIsShow?' el-icon-arrow-left':'el-icon-arrow-right']"/>
    </div>
    <!-- 上面操作导入、导出-->
    <div
      class="layout-middle"
      :style="{ width: middleWidth + 'px', height: middleHeight + 'px' }"
    >
      <div class="top-button">
        <span class="btn" @click="saveData">
          <el-tooltip
            class="item"
            effect="dark"
            content="保存"
            placement="bottom"
          >
            <i class="iconfont iconsave"></i>
          </el-tooltip>
        </span>
        <span class="btn" @click="viewScreen">
          <el-tooltip
            class="item"
            effect="dark"
            content="预览"
            placement="bottom"
          >
            <i class="iconfont iconyulan"></i>
          </el-tooltip>
        </span>

        <span class="btn" @click="handleUndo">
          <el-tooltip
            class="item"
            effect="dark"
            content="撤销"
            placement="bottom"
          >
            <i class="iconfont iconundo"></i>
          </el-tooltip>
        </span>

        <span class="btn" @click="handleRedo">
          <el-tooltip
            class="item"
            effect="dark"
            content="恢复"
            placement="bottom"
          >
            <i class="iconfont iconhuifubeifen"></i>
          </el-tooltip>
        </span>

        <span
          :class="{
            btn: true,
            'btn-disable': currentSizeRangeIndex === 0,
          }"
          @click="setSize(0)"
        >
          <el-tooltip
            class="item"
            :disabled="currentSizeRangeIndex === 0"
            effect="dark"
            content="缩小"
            placement="bottom"
          >
            <i class="el-icon-minus" style="font-size: 16px" />
          </el-tooltip>
        </span>
        <span
          :class="{
            btn: true,
            'scale-num': true,
            'btn-disable': currentSizeRangeIndex === defaultSize.index,
          }"
          @click="setSize(2)"
        >
          <el-tooltip
            class="item"
            :disabled="currentSizeRangeIndex === defaultSize.index"
            effect="dark"
            content="默认比例"
            placement="bottom"
          >
            <span> {{ parseInt(scaleNum) }}% </span>
          </el-tooltip>
        </span>
        <span
          :class="{
            btn: true,
            'btn-disable': currentSizeRangeIndex === 8,
          }"
          @click="setSize(1)"
        >
          <el-tooltip
            class="item"
            :disabled="currentSizeRangeIndex === 8"
            effect="dark"
            content="放大"
            placement="bottom"
          >
            <i class="el-icon-plus" style="font-size: 16px" />
          </el-tooltip>
        </span>

        <span class="btn" v-permission="'bigScreenManage:export'">
          <el-tooltip
            class="item"
            effect="dark"
            content="导入"
            placement="bottom"
          >
            <el-upload
              class="el-upload"
              ref="upload"
              :action="uploadUrl"
              :headers="headers"
              accept=".zip"
              :on-success="handleUpload"
              :before-upload="beforeUpload"
              :on-error="handleError"
              :show-file-list="false"
              :limit="1"
            >
              <i class="iconfont icondaoru"></i>
            </el-upload>
          </el-tooltip>
        </span>
        <span class="btn border-left" v-permission="'bigScreenManage:import'">
           <i class="iconfont icondaochu" @click="exportDashboard(1)"></i>
            <el-tooltip
              class="item"
              effect="dark"
              content="导出"
              placement="right"
            >
            </el-tooltip>
        </span>
      </div>
      <!-- 中间设计-->
      <div class="workbench-container" @mousedown="handleMouseDown">
        <div
          :style="{
            width: (+bigscreenWidth + 18) * bigscreenScaleInWorkbench + 'px',
            height: (+bigscreenHeight + 18) * bigscreenScaleInWorkbench + 'px',
          }"
          class="vue-ruler-tool-wrap"
        >
          <!-- 大屏设计页面的标尺插件 -->
          <vue-ruler-tool
            ref="vue-ruler-tool"
            v-model="dashboard.presetLine"
            class="vueRuler"
            :step-length="50"
            :parent="true"
            :position="'relative'"
            :is-scale-revise="true"
            :visible.sync="dashboard.presetLineVisible"
            :style="{
              width: +bigscreenWidth + 18 + 'px',
              height: +bigscreenHeight + 18 + 'px',
              transform:
                currentSizeRangeIndex === defaultSize.index
                  ? workbenchTransform
                  : `scale(${sizeRange[currentSizeRangeIndex] / 100})`,
              transformOrigin: '0 0',
            }"
          >
            <div
              id="workbench"
              class="workbench"
              :style="{
                width: bigscreenWidth + 'px',
                height: bigscreenHeight + 'px',
                'background-color': dashboard.backgroundColor,
                'background-image': 'url(' + dashboard.backgroundImage + ')',
                'background-position': '0% 0%',
                'background-size': '100% 100%',
                'background-repeat': 'initial',
                'background-attachment': 'initial',
                'background-origin': 'initial',
                'background-clip': 'initial',
              }"
              @click.self="setOptionsOnClickScreen"
              @drop="widgetOnDragged($event)"
              @dragover="dragOver($event)"
            >
              <div v-if="grade" class="bg-grid"></div>
              <widget
                ref="widgets"
                v-for="(widget, index) in widgets"
                :key="index"
                v-model="widget.value"
                :index="index"
                :step="step"
                :type="widget.type"
                :bigscreen="{ bigscreenWidth, bigscreenHeight }"
                @onActivated="setOptionsOnClickWidget"
                @contextmenu.prevent.native="rightClick($event, index)"
                @mousedown.prevent.native="widgetsClick(index)"
                @mouseup.prevent.native="widgetsMouseup($event, index)"
                @keyup.delete.native="entryDelete(index)"
              />
            </div>
          </vue-ruler-tool>
        </div>
      </div>
    </div>
    <!-- 右侧配置-->
    <div class="layout-right" :style="{ width: widthLeftForOptions + 'px' }">
      <el-tabs v-model="activeName" type="border-card" :stretch="true">
        <el-tab-pane
          v-if="this.isNotNull(widgetOptions.setup) || this.isNotNull(widgetOptions.collapse)"
          name="first"
          label="配置"
        >
          <dynamicForm
            ref="formData"
            :options="widgetOptions.setup"
            :layer-widget="layerWidget"
            :widget-index="widgetIndex"
            :widget-params-config="widgetParamsConfig"
            @onChanged="(val) => widgetValueChanged('setup', val)"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="isNotNull(widgetOptions.data)"
          name="second"
          label="数据"
        >
          <dynamicForm
            ref="formData"
            :options="widgetOptions.data"
            @onChanged="(val) => widgetValueChanged('data', val)"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="isNotNull(widgetOptions.position)"
          name="third"
          label="坐标"
        >
          <dynamicForm
            ref="formData"
            :options="widgetOptions.position"
            @onChanged="(val) => widgetValueChanged('position', val)"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <content-menu
      :visible.sync="visibleContentMenu"
      :style-obj="styleObj"
      @deletelayer="deletelayer"
      @lockLayer="lockLayer"
      @noLockLayer="noLockLayer"
      @copylayer="copylayer"
      @copylayerAll="copylayerAll"
      @istopLayer="istopLayer"
      @setlowLayer="setlowLayer"
      @moveupLayer="moveupLayer"
      @movedownLayer="movedownLayer"
      @setAlignment="setAlignment"
      @setTopAlignment="setTopAlignment"
      @delGroupLayer="delGroupLayer"
      @addGroupLayer="addGroupLayer"
      @delSelectMore="delSelectMore"
    />
  </div>
</template>

<script>
import {
  insertDashboard,
  detailDashboard,
  exportDashboard,
} from "@/api/bigscreen";
import { widgetTools, getToolByCode } from "./tools/index";
import widget from "./widget/widget.vue";
import dynamicForm from "./components/dynamicForm.vue";
import draggable from "vuedraggable";
import VueRulerTool from "vue-ruler-tool"; // 大屏设计页面的标尺插件
import contentMenu from "./components/contentMenu";
import { Revoke } from "@/utils/revoke";
import { getToken } from "@/utils/auth";
import { mapMutations } from 'vuex';
import { debounce } from '@/utils/debounce'; // 引入防抖函数
import loadingViewerVue from 'loading-view-vue'
import Vue from "vue";
Vue.use(loadingViewerVue,{mode:"5"});
export default {
  name: "Login",
  components: {
    draggable,
    VueRulerTool,
    widget,
    dynamicForm,
    contentMenu
  },
  data() {
    return {
      uploadUrl :"http://"+window.location.host+"/xlyReport/reportDashboard/import/" +this.$route.query.reportCode,
      grade: false,
      layerWidget: [],
      widgetTools: widgetTools, // 左侧工具栏的组件图标，将js变量加入到当前作用域
      widthLeftForTools: 200, // 左侧工具栏宽度
      widthLeftForToolsHideButton: 15, // 左侧工具栏折叠按钮宽度
      widthLeftForOptions: 300, // 右侧属性配置区
      widthPaddingTools: 18,
      toolIsShow: true, // 左侧工具栏是否显示
      bigscreenWidth: 1920, // 大屏设计的大小
      bigscreenHeight: 1080,
      widthRightForToolsHideButton: 15, // 右侧工具栏折叠按钮宽度
      setupIsShow: true, // 右侧配置是否显示
      revoke: null,

      // 工作台大屏画布，保存到表gaea_report_dashboard中
      dashboard: {
        id: null,
        title: "", // 大屏页面标题
        width: 1920, // 大屏设计宽度
        height: 1080, // 大屏设计高度
        backgroundColor: "", // 大屏背景色
        backgroundImage: "", // 大屏背景图片
        refreshSeconds: null, // 大屏刷新时间间隔
        presetLine: [], // 辅助线
        presetLineVisible: true, // 辅助线是否显示
        data: {},
      },
      masterData:{},//主表数据源
      // 大屏的标记
      screenCode: "",
      dragWidgetCode: "", //从工具栏拖拽的组件code
      // 大屏画布中的组件
      widgets: [], // 工作区中拖放的组件
      // 当前激活组件
      widgetIndex: 0,
      // 当前激活组件右侧配置属性
      widgetOptions: {
        setup: [], // 配置
        data: [], // 数据
        position: [], // 坐标
      },
      flagWidgetClickStopPropagation: false, // 点击组件时阻止事件冒泡传递到画布click事件上
      styleObj: {
        left: 0,
        top: 0,
      },
      visibleContentMenu: false,
      rightClickIndex: -1,
      activeName: "first",
      selectMore:[],//按住shift多选的图层
      shiftEnt:false,//shift键盘是否按住
      scaleNum: 0, // 当前缩放百分比的值
      sizeRange: [20, 40, 60, 80, 100, 150, 200, 300, 400], // 缩放百分比
      currentSizeRangeIndex: -1, // 当前是哪个缩放比分比,
      currentWidgetTotal: 0,
      widgetParamsConfig: [], // 各组件动态数据集的参数配置情况
    };
  },
  computed: {
    step() {
      return Number(100 / (this.bigscreenScaleInWorkbench * 100));
    },
    headers() {
      return {
        Authorization: getToken(), // 直接从本地获取token就行
      };
    },
    // 左侧、右侧折叠切换时，动态计算中间区的宽度
    middleWidth() {
      let widthLeftAndRight = 0;
      if (this.toolIsShow) {
        widthLeftAndRight += this.widthLeftForTools; // 左侧工具栏宽度
      }
      widthLeftAndRight += this.widthLeftForToolsHideButton; // 左侧工具栏折叠按钮宽度
      widthLeftAndRight += this.widthLeftForOptions; // 右侧配置栏宽度

      let middleWidth = this.bodyWidth - widthLeftAndRight;
      return middleWidth;
    },
    middleHeight() {
      return this.bodyHeight;
    },
    // 设计台按大屏的缩放比例
    bigscreenScaleInWorkbench() {
      let widthScale =
        (this.middleWidth - this.widthPaddingTools) / this.bigscreenWidth;
      let heightScale =
        (this.middleHeight - this.widthPaddingTools) / this.bigscreenHeight;
      return Math.min(widthScale, heightScale);
    },
    workbenchTransform() {
      return `scale(${this.bigscreenScaleInWorkbench}, ${this.bigscreenScaleInWorkbench})`;
    },
    // 大屏在设计模式的大小
    bigscreenWidthInWorkbench() {
      return this.getPXUnderScale(this.bigscreenWidth) + this.widthPaddingTools;
    },
    bigscreenHeightInWorkbench() {
      return (
        this.getPXUnderScale(this.bigscreenHeight) + this.widthPaddingTools
      );
    },
    // 初始的缩放百分比 和 下标
    defaultSize() {
      const obj = {
        index: -1,
        size: "50",
      };
      this.sizeRange.some((item, index) => {
        // console.log(item,index);
        if (item <= 100 * this.bigscreenScaleInWorkbench) {
          obj.index = index;
          obj.size = 100 * this.bigscreenScaleInWorkbench;
        }
      });
      if (obj.index === -1) {
        obj.index = 0;
        obj.size = this.sizeRange[0];
      }
      return obj;
    },
  },
  watch: {
    defaultSize: {
      handler(val) {
        if (val !== -1 && this.isObjectFn(val)) {
          this.currentSizeRangeIndex = val.index;
          this.scaleNum = val.size;
        }
      },
      immediate: true,
    },
    widgets: {
      handler(val) {
        this.handlerLayerWidget(val);
       // this.handlerdynamicDataParamsConfig(val);
        // console.log("刷新")
        //以下部分是记录历史
        this.$nextTick(() => {
          this.revoke.push(this.widgets);
        });
      },
      deep: true,
    },
    bigscreenWidth() {
      this.initVueRulerTool();
    },
    bigscreenHeight() {
      this.initVueRulerTool();
    },
  },
  created() {
    /* 以下是记录历史的 */
    this.revoke = new Revoke();
  },
  mounted() {
    // 如果是新的设计工作台
    this.widgets = [];
    window.addEventListener("mouseup", () => {
      this.grade = false;
    });
    this.$nextTick(() => {
      this.initVueRulerTool(); // 初始化 修正插件样式
    });
    this.initEchartData();
    window.addEventListener('keydown', code => this.handleKeyDown(code)); // 监听键盘按下事件
    window.addEventListener('keyup', code => this.handleKeyUp(code)); // 监听键盘松开事件
  },
  // 在beforeDestroy中
  beforeDestroy() {
    // 销毁监听键盘事件
    window.removeEventListener('keydown', code => this.handleKeyDown(code));
    window.removeEventListener('keyup', code => this.handleKeyUp(code));
  },
  methods: {
    ...mapMutations('dataSource', ['SET_STATIC_DATA']),
    /**
     * @param num: 0缩小 1放大 2默认比例
     * sizeRange: [20, 40, 60, 72, 100, 150, 200, 300, 400]
     */
    setSize(num) {
      switch (num) {
        case 0: this.currentSizeRangeIndex === 0 ? '' : this.currentSizeRangeIndex -= 1;
          break;
        case 1: this.currentSizeRangeIndex === 8 ? '' : this.currentSizeRangeIndex += 1;
          break;
        case 2: this.currentSizeRangeIndex = this.defaultSize.index;
      }
     // console.log(this.currentSizeRangeIndex,this.defaultSize.index,this.defaultSize.size,this.sizeRange[this.currentSizeRangeIndex])
      this.scaleNum = this.currentSizeRangeIndex === this.defaultSize.index ? this.defaultSize.size : this.sizeRange[this.currentSizeRangeIndex];
    },
    // 初始化 修正插件样式
    initVueRulerTool() {
      const vueRulerToolDom = this.$refs["vue-ruler-tool"].$el; // 操作面板 第三方插件工具
      const contentDom = vueRulerToolDom.querySelector(".vue-ruler-content");
      const vueRulerX = vueRulerToolDom.querySelector(".vue-ruler-h"); // 横向标尺
      const vueRulerY = vueRulerToolDom.querySelector(".vue-ruler-v"); // 纵向标尺
      contentDom.style.width = "100%";
      contentDom.style.height = "100%";

      let xHtmlContent = "";
      let yHtmlContent = "";
      let currentNum = 0;
      while (currentNum < +this.bigscreenWidth) {
        xHtmlContent += `<span class="n" style="left: ${currentNum + 2}px;">${currentNum}</span>`;
        currentNum += 50;
      }
      currentNum = 0;
      while (currentNum < +this.bigscreenHeight) {
        yHtmlContent += `<span class="n" style="top: ${currentNum + 2}px;">${currentNum}</span>`;
        currentNum += 50;
      }
      vueRulerX.innerHTML = xHtmlContent;
      vueRulerY.innerHTML = yHtmlContent;
    },
    // 重写默认数据
    setDefaultWidgetConfigValue(data, option) {
      this.setConfigValue(data.setup, option.setup)
      this.setConfigValue(data.position, option.position)
      this.setConfigValue(data.data, option.data)
      return option;
    },
    setConfigValue(objValue, setup) {
      Object.keys(objValue).forEach(key => {
        setup.forEach(item => {
          if (this.isObjectFn(item) && key == item.name) {
            item.value = objValue[key]
          }
          if (this.isArrayFn(item)) {
            item.forEach(itemChild => {
              itemChild.list.forEach(el => {
                if (key == el.name) {
                  el.value = objValue[key]
                }
              })
            })
          }
        })
      })
    },

    /**
     * @description: 恢复
     * @param {*}
     * @return {*}
     */
    handleUndo() {
      const record = this.revoke.undo();
      if (!record) {
        return false;
      }
      this.widgets = record;
    },
    // 监听按下键盘事件
    handleKeyDown: debounce(function(code) {
      // 判断是否按住shift键，是就把pin赋值为true
      // console.log(code)
      if (code.keyCode === 16 && code.shiftKey) {
        this.shiftEnt = true;
      }else if (
        code.keyCode === 37 ||
        code.keyCode === 38 ||
        code.keyCode === 39 ||
        code.keyCode === 40
      ) {
        //上下左右移动
        this.dragWidgetMoveByKey(code,this.widgetIndex);
      }else if (code.key=='Tab'&& code.keyCode === 9) {
        this.shiftEnt = false;
        //标记重置
        this.handleMouseDown();
      }
    }, 10, true),
    handleKeyUp: debounce(function(code) {
      // 判断是否松开shift键，是就把pin赋值为false
    }, 500, true),
    /**
     * @description: 重做
     * @param {*}
     * @return {*}
     */
    handleRedo() {
      const record = this.revoke.redo();
      if (!record) {
        return false;
      }
      this.widgets = record;
    },
    handlerLayerWidget(val) {
      const layerWidgetArr = [];
      for (let i = 0; i < val.length; i++) {
        const obj = {};
        obj.icon = getToolByCode(val[i].type).icon;
        const options = val[i].options["setup"];
        options.forEach((el) => {
          if (el.name == "layerName") {
            obj.label = el.value;
          }
        });
        layerWidgetArr.push(obj);
      }
      this.layerWidget = layerWidgetArr;
    },
    async initEchartData() {
      const reportCode = this.$route.query;
      this.$showLoading();
      const { code, data } = await detailDashboard(reportCode);
      this.$hideLoading();
      if (code != 200) return;
      const processData = this.handleInitEchartsData(data);
      const screenData = this.handleBigScreen(data.dashboard);
      this.widgets = processData;
      this.dashboard = screenData;
      this.bigscreenWidth = this.dashboard.width;
      this.bigscreenHeight = this.dashboard.height;
      //判断数据源是否配置了主数据源，如果配置了主数据，将主数据转换成静态的保存
      if(this.isNotBlankObj(screenData)){
        this.setMasterData(screenData);
        //将动态数据部分赋值
        //console.log("将动态数据部分赋值",this.widgetOptions);
        this.setWidgetOptionsData(screenData.data);
      }
    },
    // 返回每个组件的动态数据集参数配置情况
    handlerdynamicDataParamsConfig(val) {
      this.widgetParamsConfig = val.map((item) => {
        return item.value.data;
      });
    },
    // 数据处理
    setMasterData(screenData){
      // 数据类型 静态 or 动态
      const screenD = screenData.data;
      const refreshTime =  screenD["refreshTime"]||60000*30;
      screenD.dataType == "staticData"
        ? this.staticDataFn(screenD.staticData)
        : this.dynamicDataFn(screenD.dynamicData, refreshTime);
    },
    staticDataFn(val) {
      //获取静态数据
      this.masterData=val;
      this.SET_STATIC_DATA(this.masterData);
    },
    dynamicDataFn(val, refreshTime) {
      if (!val) return;
      if (this.ispreview) {
        this.getEchartData(val);
        this.flagInter = setInterval(() => {
          this.getEchartData(val);
        }, refreshTime);
      } else {
        this.getEchartData(val);
      }
    },
    getEchartData(val) {
      const data = this.queryEchartsData(val);
      data.then(res => {
        this.renderingFn(res);
      });
    },
    renderingFn(val) {
      let masterDataVal={};
      if(this.isNotBlankArray(val)){
        for (let i = 0; i < val.length; i++) {
          const one = val[i];
          const sValue = (this.isBlankObject(one)|| this.isBlank(one['sValue']))?"":one['sValue'];
          if(this.isNotBlankObj(one) && this.isNotBlank(one['sName'])){
            const sName = one['sName'];
            masterDataVal[sName]=sValue;
          }
        }
      }else{
        masterDataVal={};
      }
      this.masterData = masterDataVal;
      // console.log("masterData",masterDataVal);
      this.SET_STATIC_DATA(masterDataVal);
     // this.$forceUpdate();
    },

    handleBigScreen(data) {
      const optionScreen = getToolByCode("screen").options;
      const setup = optionScreen.setup;
      for (const key in data) {
        for (let i = 0; i < setup.length; i++) {
          if (key == setup[i].name) {
            setup[i].value = data[key];
          }
        }
      }
      this.setOptionsOnClickScreen();
      return {
        backgroundColor: (data && data.backgroundColor) || (!data ? "rgba(52, 80, 106, 1)" : ""),
        backgroundImage: (data && data.backgroundImage) || "",
        height: (data && data.height) || 1080,
        title: (data && data.title) || "",
        description: (data && data.description) || "",
        width: (data && data.width) || 1920,
        data: (data && data.data) || {},
      };
    },
    handleInitEchartsData(data) {
      const widgets = data.dashboard ? data.dashboard.widgets : [];
      const widgetsData = [];
      for (let i = 0; i < widgets.length; i++) {
        let obj = {};
        obj.type = widgets[i].type;
        obj.value = {
          setup: widgets[i].value.setup,
          data: widgets[i].value.data,
          position: widgets[i].value.position,
        };
        const tool = this.deepClone(getToolByCode(widgets[i].type));
        const option = tool.options;
        const options = this.handleOptionsData(widgets[i].value, option);
        obj.options = options;
        widgetsData.push(obj);
      }
      return widgetsData;
    },
    handleOptionsData(data, option) {
      for (const key in data.setup) {
        for (let i = 0; i < option.setup.length; i++) {
          let item = option.setup[i];
          if (Object.prototype.toString.call(item) == "[object Object]") {
            if (key == option.setup[i].name) {
              option.setup[i].value = data.setup[key];
            }
          } else if (Object.prototype.toString.call(item) == "[object Array]") {
            for (let j = 0; j < item.length; j++) {
              const list = item[j].list;
              list.forEach((el) => {
                if (key == el.name) {
                  el.value = data.setup[key];
                }
              });
            }
          }
        }
      }
      // position
      for (const key in data.position) {
        for (let i = 0; i < option.position.length; i++) {
          if (key == option.position[i].name) {
            option.position[i].value = data.position[key];
          }
        }
      }
      // data
      for (const key in data.data) {
        for (let i = 0; i < option.data.length; i++) {
          if (key == option.data[i].name) {
            option.data[i].value = data.data[key];
          }
        }
      }
      return option;
    },
    // 保存数据
    async saveData() {
      if (!this.widgets || this.widgets.length == 0) {
        this.$message.error("请添加组件");
        return;
      }
      // console.log("保存数据DATA",this.dashboard);
      const screenData = {
        reportCode: this.$route.query.reportCode,
        dashboard: {
          title: this.dashboard.title,
          width: this.dashboard.width,
          height: this.dashboard.height,
          backgroundColor: this.dashboard.backgroundColor,
          data: this.dashboard.data,
          backgroundImage: this.dashboard.backgroundImage,
        },
        widgets: this.widgets,
      };
      // console.log(screenData);
      //loading
      this.$showLoading();
      const { code } = await insertDashboard(screenData);
      this.$hideLoading();
      if (code == "200") {
        this.$message.success("保存成功！");
      }
    },
    // 预览
    viewScreen() {
      let routeUrl = this.$router.resolve({
        path: "/bigscreen/viewer",
        query: { reportCode: this.$route.query.reportCode },
      });
      window.open(routeUrl.href, "_blank");
    },
    //  导出
    async exportDashboard(val) {
      const fileName = this.$route.query.reportCode + ".zip";
      const param = {
        reportCode: this.$route.query.reportCode,
        showDataSet: val,
      };
      this.$showLoading();
      exportDashboard(param).then((res) => {
        const that = this;
        const type = res.type;
        this.$hideLoading();
        if (type == "application/json") {
          let reader = new FileReader();
          reader.readAsText(res, "utf-8");
          reader.onload = function () {
            const data = JSON.parse(reader.result);
            that.$message.error(data.message);
          };
          return;
        }
        const blob = new Blob([res], { type: "application/octet-stream" });
        if (window.navigator.msSaveOrOpenBlob) {
          //msSaveOrOpenBlob方法返回bool值
          navigator.msSaveBlob(blob, fileName); //本地保存
        } else {
          const link = document.createElement("a"); //a标签下载
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
      });
    },
    //上传之前
    beforeUpload(){
      this.$showLoading();
    },
    // 上传成功的回调
    handleUpload(response, file, fileList) {
      //清除el-upload组件中的文件
      this.$refs.upload.clearFiles();
      //刷新大屏页面
      this.initEchartData();
      this.$hideLoading();
      if (response.code == "200") {
        this.$message({
          message: "导入成功！",
          type: "success",
        });
      } else {
        this.$message({
          message: response.message,
          type: "error",
        });
      }
    },
    handleError(err) {
      this.$hideLoading();
      this.$message({
        message: "上传失败！",
        type: "error",
      });
    },
// 在缩放模式下的大小
    getPXUnderScale(px) {
      return this.bigscreenScaleInWorkbench * px;
    },
    dragStart(widgetCode) {
      this.dragWidgetCode = widgetCode;
      this.currentWidgetTotal = this.widgets.length; // 当前操作面板上有多少各组件
    },
    dragEnd() {
      /**
       * 40@remarks 新增组件到操作面板后，右边的配置有更新，但是当前选中的组件没更新，导致配置错乱的bug;
       * 由于拖动组件拖到非操作面板上是不会添加组件，还需判断是否添加组件到操作面板上;
       */
      this.$nextTick(() => {
        if (this.widgets.length === this.currentWidgetTotal + 1) {
          // 确实新增了一个组件到操作面板上
          // console.log(
          //   `新添加 '${
          //     this.widgets[this.currentWidgetTotal].value.setup.layerName
          //   }' 组件到操作面板`
          // );
          const uuid = Number(Math.random().toString().substr(2)).toString(36);
          this.widgets[this.currentWidgetTotal].value.widgetId = uuid;
          this.layerWidget[this.currentWidgetTotal].widgetId = uuid;
          this.widgets[this.currentWidgetTotal].value.widgetCode = this.dragWidgetCode;
          const index = this.widgets.length - 1;
          this.layerClick(index); // 选中当前新增的组件
          this.grade = false; // 去除网格线
        }
      });
    },
    dragOver(evt) {
      evt.preventDefault();
      evt.stopPropagation();
      evt.dataTransfer.dropEffect = "copy";
    },
    // 拖动一个组件放到工作区中去，在拖动结束时，放到工作区对应的坐标点上去
    widgetOnDragged(evt) {
      let widgetType = this.dragWidgetCode;

      // 获取结束坐标和列名
      let eventX = evt.clientX; // 结束在屏幕的x坐标
      let eventY = evt.clientY; // 结束在屏幕的y坐标

      let workbenchPosition = this.getDomTopLeftById("workbench");
      let widgetTopInWorkbench = eventY - workbenchPosition.top;
      let widgetLeftInWorkbench = eventX - workbenchPosition.left;

      const targetScale =
        this.currentSizeRangeIndex === this.defaultSize.index
          ? this.bigscreenScaleInWorkbench
          : this.sizeRange[this.currentSizeRangeIndex] / 100;
      const x = widgetLeftInWorkbench / targetScale;
      const y = widgetTopInWorkbench / targetScale;

      // 复制一个组件
      let tool = getToolByCode(widgetType);
      let widgetJson = {
        type: widgetType,
        value: {
          setup: {},
          data: {},
          position: {
            width: 0,
            height: 0,
            left: 0,
            top: 0,
            zIndex: 0,
          },
        },
        options: tool.options,
      };
      // 处理默认值
      const widgetJsonValue = this.getWidgetConfigValue(widgetJson);

      //可以拖拽放到鼠标的位置
      widgetJsonValue.value.position.left =
        x - widgetJsonValue.value.position.width / 2;
      widgetJsonValue.value.position.top =
        y - widgetJsonValue.value.position.height / 2;

      // 将选中的复制组件，放到工作区中去
      this.widgets.push(this.deepClone(widgetJsonValue));
      // 激活新组件的配置属性
      this.setOptionsOnClickWidget(this.widgets.length - 1);
    },
    getWidgetConfigValue(widgetJson) {
      this.setWidgetConfigValue(
        widgetJson.options.setup,
        widgetJson.value.setup
      );
      this.setWidgetConfigValue(
        widgetJson.options.position,
        widgetJson.value.position
      );
      this.setWidgetConfigValue(widgetJson.options.data, widgetJson.value.data);
      return widgetJson;
    },
    setWidgetConfigValue(config, configValue) {
      if (config && config.length) {
        config.forEach((item) => {
          if (this.isObjectFn(item)) {
            configValue[item.name] = item.value;
          }
          if (this.isArrayFn(item)) {
            item.forEach((itemChild) => {
              itemChild.list.forEach((ev) => {
                configValue[ev.name] = ev.value;
              });
            });
          }
        });
      }
    },
    // 对组件默认值处理
    handleDefaultValue(widgetJson) {
      for (const key in widgetJson) {
        if (key == "options") {
          // collapse、data、position、setup
          // setup 处理
          for (let i = 0; i < widgetJson.options.setup.length; i++) {
            const item = widgetJson.options.setup[i];
            if (Object.prototype.toString.call(item) == "[object Object]") {
              widgetJson.value.setup[item.name] = item.value;
            } else if (
              Object.prototype.toString.call(item) == "[object Array]"
            ) {
              for (let j = 0; j < item.length; j++) {
                const list = item[j].list;
                list.forEach((el) => {
                  widgetJson.value.setup[el.name] = el.value;
                });
              }
            }
          }
          // position
          for (let i = 0; i < widgetJson.options.position.length; i++) {
            const item = widgetJson.options.position[i];
            if (item.value) {
              widgetJson.value.position[item.name] = item.value;
            }
          }
          // data 处理
          if (widgetJson.options.data && widgetJson.options.data.length > 0) {
            for (let i = 0; i < widgetJson.options.data.length; i++) {
              const item = widgetJson.options.data[i];
              if (item.value) {
                widgetJson.value.data[item.name] = item.value;
              }
            }
          }
        }
      }
      // console.log("widgetJson",widgetJson);
      return widgetJson;
    },
    layerClick(index) {
      this.widgetIndex = index;
      this.widgetsClick(index);
    },
    // 如果是点击大屏设计器中的底层，加载大屏底层属性
    setOptionsOnClickScreen() {
      if(!this.shiftEnt) {
        this.screenCode = "screen";
        // 选中不同的组件 右侧都显示第一栏
        this.activeName = "first";
        this.widgetOptions = getToolByCode("screen")["options"];
      }
    },
    getScreenData(data){
      const screenData = {};
      if(this.isNotBlankArray(data)){
        for (let i = 0; i < data.length; i++) {
          const one =data[i];
          screenData[one.name]=one.value;
        }
      }
      return screenData;
    },

    // 如果是点击某个组件，获取该组件的配置项
    setOptionsOnClickWidget(obj) {
      this.screenCode = "";
      if (typeof obj == "number") {
        this.widgetOptions = {};
        // 直接赋值数据不刷新。。。
        this.$nextTick(() => {
          this.widgetOptions = this.deepClone(this.widgets[obj]["options"]);
        });
        return;
      }
      if (obj.index < 0 || obj.index >= this.widgets.length) {
        return;
      }
      this.widgetIndex = obj.index;
      let leftNew =  obj.left;
      let topNew =  obj.top;
      let leftOld =  this.widgets[obj.index].value.position.left;
      let topOld = this.widgets[obj.index].value.position.top;
      this.widgets[obj.index].value.position = obj;
      this.widgets[obj.index].options.position.forEach((el) => {
        for (const key in obj) {
          if (el.name == key) {
            el.value = obj[key];
          }
        }
      });
      this.widgetOptions = this.deepClone(this.widgets[obj.index]["options"]);
      if(this.shiftEnt){
        //批量移动
        this.moveGroup(leftOld,leftNew,topOld,topNew);
      }
    },
    widgetsClick(index) {
      const draggableArr = this.$refs.widgets;
      //判断是否按住了shift键盘
      if(this.shiftEnt){
        for (let i = 0; i < draggableArr.length; i++) {
          if (i == index) {
            this.$refs.widgets[i].$refs.draggable.setActive(true);
            this.selectMore.push(index);
          }
        }
      }else{
        //没有按住shift键标识编辑单个
        let selectMore = [];
        for (let i = 0; i < draggableArr.length; i++) {
          if (i == index) {
            this.$refs.widgets[i].$refs.draggable.setActive(true);
            selectMore.push(index);
            this.selectMore = selectMore;
          } else {
            this.$refs.widgets[i].$refs.draggable.setActive(false);
          }
        }
      }
      this.setOptionsOnClickWidget(index);
      this.grade = true;
      this.widgetIndex = index;
    },
    widgetsMouseup(event, index) {
      this.grade = false;
    },
    handleMouseDown() {
      if(!this.shiftEnt){
        const draggableArr = this.$refs.widgets;
        for (let i = 0; i < draggableArr.length; i++) {
          this.$refs.widgets[i].$refs.draggable.setActive(false);
        }
        this.selectMore = [];
      }
    },
    setWidgetOptionsData(val){
      let newData = new Array();
      const cloneVal = this.deepClone(val);
      this.widgetOptions.data.forEach((el) => {
        if (Object.hasOwn(cloneVal, el.name)) {
          el["value"] = cloneVal[el.name];
        }
        newData.push(el);
      });
      this.widgetOptions.data = newData;
    },
    // 将当前选中的组件，右侧属性值更新
    widgetValueChanged(key, val) {
      if (this.screenCode == "screen") {
        if (key === 'setup') {
          // 全局配置更改
          let newSetup = new Array();
          this.dashboard = this.deepClone(val);
          if (this.bigscreenWidth !== this.dashboard.width && this.dashboard.width) {
            this.bigscreenWidth = this.dashboard.width;
          }
          if (this.bigscreenHeight !== this.dashboard.height && this.dashboard.height) {
            this.bigscreenHeight = this.dashboard.height;
          }

          this.widgetOptions.setup.forEach((el) => {
            if (el.name == "width") {
              el.value = this.bigscreenWidth;
            } else if (el.name == "height") {
              el.value = this.bigscreenHeight;
            } else if (Object.hasOwn(this.dashboard, el.name)) {
              el["value"] = this.dashboard[el.name];
            }
            newSetup.push(el);
          });
          this.widgetOptions.setup = newSetup;
        } else if (key === 'data') {
          // 全局数据更改
          this.dashboard.data=val;
          let newData = new Array();
          const cloneVal = this.deepClone(val);
          this.widgetOptions.data.forEach((el) => {
            if (Object.hasOwn(cloneVal, el.name)) {
              el["value"] = cloneVal[el.name];
            }
            newData.push(el);
          });
          this.widgetOptions.data = newData;
          if(val
            && this.isNotBlankObj(val.dynamicData)
            && "master-data"===val.dynamicData.chartType){
            this.setMasterData(this.dashboard);
          }
        }
      } else {
        for (let i = 0; i < this.widgets.length; i++) {
          if (this.widgetIndex == i) {
            if(this.shiftEnt && val && val.hasOwnProperty("left") && val.hasOwnProperty("top")){
              const obj = this.widgets[i].value.position;
              const leftOld = obj.left;
              const leftNew = val.left;
              const topOld = obj.top;
              const topNew = val.top;
              this.moveGroup(leftOld,leftNew,topOld,topNew);
            }
            this.widgets[i].value[key] = this.deepClone(val);
            this.setDefaultValue(this.widgets[i].options[key], val);
          }
        }
      }
    },
    // 右键
    rightClick(event, index) {
      this.rightClickIndex = index;
      const left = event.clientX;
      const top = event.clientY;
      if (left || top) {
        this.styleObj = {
          left: left + "px",
          top: top + "px",
          display: "block",
        };
      }
      this.visibleContentMenu = true;
      return false;
    },
    setDefaultValue(options, val) {
      for (let i = 0; i < options.length; i++) {
        if (Object.prototype.toString.call(options[i]) == "[object Object]") {
          for (const k in val) {
            if (options[i].name == k) {
              options[i].value = val[k];
            }
          }
        } else if (
          Object.prototype.toString.call(options[i]) == "[object Array]"
        ) {
          for (let j = 0; j < options[i].length; j++) {
            const list = options[i][j].list;
            for (let z = 0; z < list.length; z++) {
              for (const k in val) {
                if (list[z].name == k) {
                  list[z].value = val[k];
                }
              }
            }
          }
        }
      }
    },
    datadragEnd(evt) {
      evt.preventDefault();
      this.widgets = this.swapArr(this.widgets, evt.oldIndex, evt.newIndex);
    },
    // 数组 元素互换位置
    swapArr(arr, oldIndex, newIndex) {
      arr[oldIndex] = arr.splice(newIndex, 1, arr[oldIndex])[0];
      return arr;
    },
    //去重
    setUnique(arr) {
      let newArr = [];
      arr.forEach(item => {
        return newArr.includes(item) ? '' : newArr.push(item);
      });
      return newArr;
    },
    // 多选复制
    copylayer() {
      //首先复制右选节点，再复制其他选择节点
      this.copylayerOne(this.rightClickIndex)
      // if(this.isNotBlankArray(this.selectMore)){
      //    for(let i = 0; i< this.selectMore.length;i++){
      //       const copyIndex = this.selectMore[i];
      //       if(this.rightClickIndex != copyIndex){
      //         this.copylayerOne(copyIndex);
      //       }
      //    }
      // }
    },  // 多选复制
    copylayerAll() {
      //首先复制右选节点，再复制其他选择节点
      // this.copylayerOne(this.rightClickIndex)
      if(this.isNotBlankArray(this.selectMore)){
         for(let i = 0; i< this.selectMore.length;i++){
            const copyIndex = this.selectMore[i];
            if(this.rightClickIndex != copyIndex){
              this.copylayerOne(copyIndex);
            }
         }
      }
    },
    // 复制
    copylayerOne(index) {
      const obj = this.deepClone(this.widgets[index]);
      this.widgets.splice(this.widgets.length, 0, obj);
    },
    // 置顶
    istopLayer() {
      if (this.rightClickIndex + 1 < this.widgets.length) {
        const temp = this.widgets.splice(this.rightClickIndex, 1)[0];
        this.widgets.push(temp);
      }
    },
    // 置底
    setlowLayer() {
      if (this.rightClickIndex != 0) {
        this.widgets.unshift(this.widgets.splice(this.rightClickIndex, 1)[0]);
      }
    },
    // 上移一层
    moveupLayer() {
      if (this.rightClickIndex != 0) {
        this.widgets[this.rightClickIndex] = this.widgets.splice(
          this.rightClickIndex - 1,
          1,
          this.widgets[this.rightClickIndex]
        )[0];
      } else {
        this.widgets.push(this.widgets.shift());
      }
    },
    // 下移一层
    movedownLayer() {
      if (this.rightClickIndex != this.widgets.length - 1) {
        this.widgets[this.rightClickIndex] = this.widgets.splice(
          this.rightClickIndex + 1,
          1,
          this.widgets[this.rightClickIndex]
        )[0];
      } else {
        this.widgets.unshift(this.widgets.splice(this.rightClickIndex, 1)[0]);
      }
    },
    showDialogBoxInput() {
      this.$prompt('请输入分组名称', '提示',
        {confirmButtonText: '确定',cancelButtonText: '取消'}).then(({ value }) => {
        if (!value || value.length > 20) {
          return this.$message.error('请输入不超过20字的分组名称')
        }
        const msg = "您输入了分组名称为："+value;
        this.$message({type: 'info', message: msg});

        //移除全选的选中
        this.delSelectMore();

      }).catch(() => {
        //this.$message({type: 'info', message: '取消操作'});
      })

    },
    //添加分组
    addGroupLayer() {
      // const obj = this.widgets[this.rightClickIndex];
      // this.$set(obj.value.position, "disabled", true);
      // 显示输入弹框
      this.showDialogBoxInput();
      // this.$message({
      //   type: "info",
      //   message: "小编正在努力开发中，尽情期待(可以选择多选后改变坐标移动哦)",
      // });

    },
    //移除分组
    delGroupLayer() {
      this.$message({
        type: "info",
        message: "小编正在努力开发中，尽情期待(可以选择多选后改变坐标移动哦)",
      });
    },
    //水平对齐
    setTopAlignment() {
      this.selectMore = this.setUnique(this.selectMore);
      if(!this.shiftEnt || !this.selectMore){
        this.$message({
          type: "info",
          message: "对不起，水平对齐只能多选情况下使用",
        });
        return;
      }
      const obj = this.widgets[this.widgetIndex];
      const topNew = obj.value.position.top;
      if(this.isNotBlankArray(this.selectMore)){
        for(let i = 0; i< this.selectMore.length;i++){
          const index = this.selectMore[i];
          if(this.widgetIndex != index){
            this.widgets[index].value.position.top=topNew;
            this.$refs.widgets[index].$refs.draggable.setActive(false);
          }
        }
        this.setShiftEntFalse();
      }
    },
    //移除选中
    delSelectMore(){
      if(this.isNotBlankArray(this.selectMore)){
        for(let i = 0; i< this.selectMore.length;i++){
          const index = this.selectMore[i];
          this.$refs.widgets[index].$refs.draggable.setActive(false);
        }
        this.setShiftEntFalse();
      }
    },
    //左对齐
    setAlignment() {
      this.selectMore = this.setUnique(this.selectMore);
      if(!this.shiftEnt || !this.selectMore){
        this.$message({
          type: "info",
          message: "对不起，左对齐只能多选情况下使用",
        });
        return;
      }
      const obj = this.widgets[this.widgetIndex];
      const leftNew = obj.value.position.left;
      if(this.isNotBlankArray(this.selectMore)){
         for(let i = 0; i< this.selectMore.length;i++){
            const index = this.selectMore[i];
            if(this.widgetIndex != index){
              this.widgets[index].value.position.left=leftNew;
              this.$refs.widgets[index].$refs.draggable.setActive(false);
            }
         }
        this.setShiftEntFalse();
      }
    },
    //输入坐标选中的整体移动
    moveGroup(leftOld,leftNew,topOld,topNew) {
      this.selectMore = this.setUnique(this.selectMore);
      if(this.isNotBlankArray(this.selectMore)){
        const leftDiff = leftNew - leftOld;
        const topDiff = topNew - topOld;
        for(let i = 0; i< this.selectMore.length;i++){
          const index = this.selectMore[i];
          if(this.widgetIndex != index){
            this.widgets[index].value.position.left=this.widgets[index].value.position.left+leftDiff;
            this.widgets[index].value.position.top=this.widgets[index].value.position.top+topDiff;
            //移除锁定标记
            // this.$refs.widgets[index].$refs.draggable.setActive(false);
          }
        }
        // this.setShiftEntFalse();
      }
    },
    setShiftEntFalse(){
      this.shiftEnt = false;
      this.selectMore = [];
    },
    //输入删除键删除
    entryDelete(index){
      // this.widgets.splice(index, 1);
      this.selectMore = this.setUnique(this.selectMore);
      //首先复制右选节点，再复制其他选择节点
      let widgetsCp = [];
      if(this.isNotBlankArray(this.selectMore)){
        for(let i = 0; i< this.widgets.length;i++){
          if(this.selectMore.indexOf(i)<0 && index!=i){
            widgetsCp.push(this.widgets[i]);
          }
        }
      }
      this.widgets = widgetsCp;
      this.setShiftEntFalse();
    },
    deletelayer() {
      this.deletelayerMore();
      //this.widgets.splice(this.rightClickIndex, 1);
    },
    // 删除
    deletelayerMore() {
      //键盘输入删除
      this.entryDelete(this.rightClickIndex);
    },
    // 锁定
    lockLayer() {
      const obj = this.widgets[this.rightClickIndex];
      this.$set(obj.value.position, "disabled", true);
    },
    // 解除锁定
    noLockLayer() {
      const obj = this.widgets[this.rightClickIndex];
      this.$set(obj.value.position, "disabled", false);
    },
    //根据上下左右键移动(因为子组件直接切换焦点事件问题,这里弥补不点大屏直接切组件移动)
    dragWidgetMoveByKey(code,widgetIndex){
      const position = this.widgets[widgetIndex].value.position;
      const temp=3;
      if(code.keyCode==40 || code.key=='ArrowDown'){
        position.top = position.top+temp;
        this.$refs.widgets[widgetIndex].$refs.draggable.setTop(position);
      }if(code.keyCode==38 || code.key=='ArrowUp'){
        position.top = position.top-temp;
        this.$refs.widgets[widgetIndex].$refs.draggable.setTop(position);
      }if(code.keyCode==37 || code.key=='ArrowLeft'){
        position.left = position.left-temp;
        this.$refs.widgets[widgetIndex].$refs.draggable.setLeft(position);
      }if(code.keyCode==39 || code.key=='ArrowRight'){
        position.left = position.left+temp;
        this.$refs.widgets[widgetIndex].$refs.draggable.setLeft(position);
      }
    },
    //输入ctrl+c
    entryCopy(index){
      const obj = this.deepClone(this.widgets[index]);
      this.widgets.splice(this.widgets.length, 0, obj);
    }
  },
};
</script>

<style scoped lang="scss">
@import "@/assets/styles/screen.scss";
</style>
