<template>
  <draggable class="dragArea" item-key="id" :list="contentList" :style="setDragAreaFlex()" :id="this.dynamicConfig.id" :sort="true" group="people" @change="chageDrag" v-bind="dragOptions" :move="onMove">
        <template #item="{ element }">
            <div class="drag-tool" @click="active(element)" :id="element.id" :class="{active: element.id === currentModule.id}" :style="getActiveStyle(element)">
                <div class="drag-mask" ></div>
                <div class="drag-l">
                  <div class="drag-btn _fc-drag-btn" style="cursor: move;">
                      <i class="fc-icon icon-move"></i>
                  </div>
                </div>
                <div class="drag-r">
                  <!-- <div class="drag-btn" @click="$emit('add')">
                      <i class="fc-icon icon-add"></i>
                  </div> -->
                  <!-- <div class="drag-btn" @click="operate('copy', element)">
                      <i class="fc-icon icon-copy"></i>
                  </div> -->
                  <div class="drag-btn drag-btn-danger" @click="operate('delete', element)">
                      <i class="fc-icon icon-delete"></i>
                  </div>
                </div>
                <div v-if="element.category === 0">
                  <sc-designer-form ref="formRef" :item="element" />
                </div>
            </div>
        </template>
    </draggable>
</template>

<script>
import draggable from 'vuedraggable'
import designerInfo from '@/config/designer';
import tool from '@/utils/tool';
export default {
    name: 'DragTool',
    components: {
      draggable,
    },
    props: {
			dynamicConfig: { type: Object, default: () => {} },
		},
    data() {
      return {
          //noBindFieldList: ['space','label','divider'],
          contentList:[],
          currentModule: {},
          initHeightData: true,
      };
    },
		mounted() {
			if (Object.keys(this.dynamicConfig).length > 0){
				this.render()
			}
		},
    created() {
        window.addEventListener('keydown', this.keyOperateClick, false);
        this.$nextTick(() => {
          this.caculateTableHeight();
            var conHeight = document.getElementById("contentDragToolDiv").scrollHeight;
            var headHeight = document.getElementById("headerDragToolDiv").scrollHeight;
            var footerHeight = document.getElementById("footerDragToolDiv").scrollHeight;
            if (conHeight < 400) 
            {
              document.getElementById("contentDragToolDiv").style.height = "998px";
              document.getElementById("mainBody").style.height = (1178 + headHeight + footerHeight) + "px";
            }
            else 
            {
              document.getElementById("contentDragToolDiv").style.height = (conHeight + 150) + "px";
              document.getElementById("mainBody").style.height = (conHeight + headHeight + footerHeight + 330) + "px";
            }
            // var initBottomHeight = document.body.scrollHeight - document.documentElement.clientHeight - 30;
            // document.getElementById("footerScroll").style.bottom = initBottomHeight + "px";
        });
    },
    unmounted() {
        window.removeEventListener('keydown', this.keyOperateClick, false);
    },
    methods: {
      //快捷键操作
      keyOperateClick(e) {
        if ((e.key === 'Delete')) { 
          if (this.contentList.indexOf(this.currentModule) >= 0) {
            this.contentList.splice(this.contentList.indexOf(this.currentModule), 1)
          }
          // 阻止默认事件
          e.preventDefault();
        }
        // if (this.currentModule && this.currentModule.name === "label")
        // {
        //   console.log("lable",this.currentModule.result.offsetWidth);
        //   var lblOffsetWidth = document.getElementById(this.currentModule.id).offsetWidth - 1;
        //   this.currentModule.result.offsetWidth = lblOffsetWidth;
        //   console.log("lable1",lblOffsetWidth);
        // }
      },
      //设定当前有效标签
      active(ele) {
        if (ele) {
          if (ele.result.parentName && ele.result.parentName === "ultrasoundImageList") {
            return;
          }
          if (this.currentModule && this.currentModule.result && this.currentModule.result.property)
          {
            this.currentModule = ele;
            this.bindActiveModuleClick(true);
            this.bindParentId();
          }
        }        
      },
      bindParentId() {
        if (this.currentModule)
        {
          this.contentList.some(c => { 
            if (this.currentModule.id === c.id)
            {
              c.result.parentId = this.dynamicConfig.id;
              c.result.parentName = this.dynamicConfig.name;
              this.currentModule.result.parentId = c.result.parentId;
              this.currentModule.result.parentName = c.result.parentName;
              return true;
            }
          });
          this.$emit("updateParentId", this.dynamicConfig.id, this.contentList, this.currentModule);
        }
      },
      //拖拽触发事件
      chageDrag(item) {
        if (item){
          //表示移动
          if (item.moved)
          {
            this.currentModule = item.moved.element;
          }
          //表示新增
          else if (item.added)
          {
            this.currentModule = item.added.element;
          }
          this.bindActiveModuleClick(false);
          this.bindModuleAttribute();
          var curOffsetWidth = document.getElementById(this.currentModule.id).offsetWidth - 1;
          this.bindModuleHeight(curOffsetWidth);
        }
      },
      //操作
      operate(type, ele) {
        var index = -1;
        this.contentList.some((item, i) => {
          if (item.id === ele.id)
          {
            index = i;
            return true;
          }
        });
        //删除
        if (type === "delete")
        {
          if (index >= 0)
          {
            this.currentModule = {}
            this.contentList.splice(index, 1)
          }
          var curDom = document.getElementById(ele.result.parentId);
          if (curDom) {
            curDom.style.minHeight = "35px";
          }

          var curOffsetWidth = document.getElementById(ele.id).offsetWidth - 1;
          this.bindModuleHeight(curOffsetWidth);
        }
        //复制
        else if (type === "copy")
        {
          if (index >= 0)
          {
            var newModule = designerInfo.initAppointModule(ele.name);
            this.contentList.splice((index + 1), 0, newModule);
          }
        }
        this.bindModuleAttribute();
      },
      //回调父页面，绑定选中组件事件
      bindActiveModuleClick(flag){
        if (this.currentModule)
        {
            this.$emit("activeModuleClick", 0, this.currentModule, flag, this.dynamicConfig.id)
        }
      },
      bindModuleHeight(width) {
        this.$emit("setGridModuleWidthClick", this.currentModule.id, width, this.dynamicConfig.id)
      },
      //回调父页面，绑定值
      bindModuleAttribute() {
        if (this.currentModule)
        {
          this.contentList.some(c => { 
            if (this.currentModule.id === c.id)
            {
              c.result.parentId = this.dynamicConfig.id;
              c.result.parentName = this.dynamicConfig.name;
              this.currentModule.result.parentId = c.result.parentId;
              this.currentModule.result.parentName = c.result.parentName;
              return true;
            }
          });
          this.$emit("activeModuleClick", 1, this.currentModule, null, this.dynamicConfig.id, this.contentList);
        }
      },
      //子组件选中事件
      taksActiveModuleClick(ele) {
        this.currentModule = ele;
      },
      // //动态数据绑定加载，index页调用
      // loadDynamicObj(dynamicObj) {
			// 	this.currentModule = dynamicObj;
      //   //重置右侧数据源
      //   this.contentList.map(c => {
      //     if (c.id === this.currentModule.id)
      //     {
      //       c = this.currentModule;
      //       return false;
      //     }
      //   })
      // },
      //页面数据导入
      render() {
        if (this.dynamicConfig && this.dynamicConfig.result && this.dynamicConfig.result.tasks && this.dynamicConfig.result.tasks.length > 0)
        {
          this.dynamicConfig.result.tasks.map(c => {
            this.contentList.push(c);
          });
        }
			},
      //排序或者重新加载数据
      sortRender(list, curModuleInfo) {
        if (list && list.length > 0)
        {
          this.contentList = [];
          list.map(c => {
            this.contentList.push(c);
          });
        }
        else
        {
          this.contentList =[];
        }
        if (curModuleInfo && curModuleInfo.id && curModuleInfo.id.length > 0) {
          this.currentModule = curModuleInfo;
        }
      },
      // //清空选中
      // clearActiveModuel(dynamicObj) {
			// 	this.currentModule = dynamicObj;
      // },
      //移动
      onMove(ele){
        var targetElement = ele.draggedContext.element;
        if (ele.relatedContext.list.length <= 0)
        {
            //表示为字容器，只能接收基础组件和报告组件
            if (targetElement.name === "grid" || targetElement.name === "table") {
                return false;
            }
            else {
                return true;
            }
        }
        else
        {
            //表示主容器内容为空,为拖拽的第一个组件，此时主容器只能接收布局组件
            var targetElementItem = ele.relatedContext.list[0];
            if (targetElementItem.name === "grid" || targetElementItem.name === "table") {
                //表明是主容器，只能接收布局组件
                if (targetElementItem.name === targetElement.name)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else {
                //子容器，只能接收基础组件和报告组件
                if (targetElement.name === "grid" || targetElement.name === "table") {
                    return false;
                }
                else {
                    return true;
                }
            }
        }
      },
      //设置当前组件宽度和水平位置
			getActiveStyle(item) {
        //min-width:24.6%;
        var styleInfo = "margin-top:1px;";
        if (item.name === "label")
        {
            styleInfo += "display:flex;align-items: flex-end;";
        }
        if (item.result.pattern.width > 0) {
          if (item.name === "select" || item.name === "space")
          {
            if (this.currentModule.id === item.id)
            {
              var tempWidth = parseFloat(tool.mmToPx(item.result.pattern.width - 1)) + 50;
              styleInfo += "width:" + tempWidth + "px;";
            }
            else {
              styleInfo += "width:" + tool.mmToPx(item.result.pattern.width - 1) + "px;";
            }
          } 
          else if (item.name === "datetime")
          {
            var widthValue = 0;
						var displayFormat = item.result.property.displayFormat;
            if (displayFormat === "yyyy-MM-dd" || displayFormat === "yyyy/MM/dd" || displayFormat === "yyyy.MM.dd")
            {
                widthValue = 20;
            }
            else if (displayFormat === "yyyy年MM月dd日")
            {
                widthValue = 27;
            }
            else if (displayFormat === "yyyy-MM-dd hh:mm")
            {
                widthValue = 30;
            }
            else
            {
                widthValue = 37;
            }
            styleInfo += "width:" + (tool.mmToPx(widthValue)) + "px;";
          }
          else if (item.name === "label")
          {
            if (parseInt(item.result.pattern.width) === 0 && item.result.property.placeholder.length > 0) {
							var labelWidth = 0; 
              if (item.result.pattern.fontSize > 10.5) {
                labelWidth = parseFloat(tool.getCharCount(item.result.property.placeholder) * 4.4);
              }
              else {
                labelWidth = parseFloat(tool.getCharCount(item.result.property.placeholder) * 3.6);
              }
              styleInfo += "width:" + (tool.mmToPx(labelWidth) + 5) + "px;";
              if (item.result.property.placeholder.length >= 3) {
                styleInfo += "min-width:52px;";
              }
            }
            else {
              styleInfo += "width:" + tool.mmToPx(item.result.pattern.width - 1) + "px;";
            }
          }
          else {
            styleInfo += "width:" + tool.mmToPx(item.result.pattern.width) + "px;";
          }
        }
        if (this.dynamicConfig && this.dynamicConfig.name && this.dynamicConfig.name === "ultrasoundImageList") {
          if (this.dynamicConfig.result && this.dynamicConfig.result.pattern && this.dynamicConfig.result.pattern.showImageInterval) {
            styleInfo += "margin-left:4px;"
          }
          else {
            styleInfo += "margin-left:0px;"
          }
        }
        else if (this.dynamicConfig && this.dynamicConfig.name && this.dynamicConfig.name === "doctorInfo") {
          styleInfo += "margin-left:0px;"
        }
        else {
          if (this.dynamicConfig && this.dynamicConfig.result && this.dynamicConfig.result.pattern && this.dynamicConfig.result.pattern.interval > 1)
          {
            var curIndex = this.contentList.findIndex((t) => t.id == item.id)
            if (curIndex > 0) {
              styleInfo += "margin-left:" + tool.mmToPx(this.dynamicConfig.result.pattern.interval) + "px;"
            }
            else {
              styleInfo += "margin-left:0px;"
            }
          }
          else {
            styleInfo += "margin-left:0px;"
          }
        }
        var curDom = document.getElementById("Task"+item.result.parentId);
        if (curDom) {
          curDom.style.minHeight = "35px";
        }
        if (item.name === "divider")
        {
          styleInfo += "min-height:16px;";
					if (curDom) {
						curDom.style.minHeight = "0px";
					}
        }
        return styleInfo;
			},
      async caculateTableHeight() {
        if(this.contentList && this.contentList.length > 0) {
          this.contentList.forEach(d => {
              var curOffsetWidth = document.getElementById(d.id).offsetWidth - 1;
              if (d.name === "label") 
              {
                var rowPerHeight1 = parseFloat(d.result.pattern.fontSize) + 6;
                if (rowPerHeight1 < 20)
                {
                    rowPerHeight1 = 20;
                } 
                var lblHeight = document.getElementById(d.id).offsetHeight;
                if (lblHeight > 60 && d.result.offsetHeight < lblHeight)
                {
                    if (parseFloat(d.result.pattern.fontSize) <= 20)
                    {
                        var rowCount1 = lblHeight / 36;
                        d.result.offsetHeight = rowPerHeight1 * rowCount1;
                    }
                }
              }
              this.$emit("setGridModuleWidthClick", d.id, curOffsetWidth, this.dynamicConfig.id)
          })
        }
      },
      setDragAreaFlex() {
        var styleInfo = "";
        if (this.dynamicConfig && this.dynamicConfig.result && this.dynamicConfig.result.pattern && this.dynamicConfig.result.pattern.horizontalAlignment 
            && this.dynamicConfig.result.pattern.horizontalAlignment.length > 0)
        {
          switch(this.dynamicConfig.result.pattern.horizontalAlignment)
						{
							case "Right":
							  styleInfo += "justify-content:right";
								break;
							case "Center":
								styleInfo += "justify-content:center";
								break;
							case "Bothends":
								styleInfo += "justify-content:space-between";
								break;
							default:
								styleInfo += "justify-content:left";
								break;
						}
        }
        return styleInfo
      }
    },
    computed: {
      dragOptions() {
        return {
            animation: 200,
            group: "people",
            disabled: false,
            ghostClass: "ghost"
        };
      },
    }
};
</script>

<style>
.drag-tool {
  position: relative;
  min-height: 20px;
  box-sizing: border-box;
  padding: 2px;
  outline: 1px dashed #2E73FF;
  overflow: hidden;
  word-wrap: break-word;
  word-break: break-all;
}

.drag-tool .drag-tool {
  margin: 5px;
}

.drag-tool + .drag-tool {
  margin-top: 5px;
}

.drag-tool.active {
  outline: 1px solid #2E73FF;
}

.drag-tool.active > div > .drag-btn {
  display: flex;
}

.drag-tool .drag-btn {
  display: none;
}

.drag-r {
  position: absolute;
  right: 2px;
  bottom: 2px;
  z-index: 1904;
}

.drag-l {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1904

}

.drag-btn {
  height: 18px;
  width: 18px;
  color: #fff;
  background-color: #2E73FF;
  text-align: center;
  line-height: 20px;
  padding-bottom: 1px;
  float: left;
  cursor: pointer;
  justify-content: center;
}

.drag-btn + .drag-btn {
  margin-left: 2px;
}

.drag-btn-danger {
  background-color: #FF2E2E;
}

.drag-btn i {
  font-size: 13px;
}

.drag-mask{
    z-index: 1900;
    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom: 0;
;}

.dragArea {
  min-height: 35px;
  width: 100%;
  display: flex;
  justify-content: left;
  flex-wrap: wrap;
}
</style>
