<template>
  <div
    class="root_unit bg-white"
    style="margin-top: 10px"
    v-if="unit.title !== 'ext'"
  >
    <h2
      class="title flex items-center"
      @click="emitSelect(unit)"
      draggable="false"
      :class="{
        'show-border-bottom':
          unit.children && unit.children.length !== 0 && open,
      }"
    >
      <div style="width: 15px; margin-right: 12px" draggable="false">
        <img
          v-if="unit.children && unit.children.length !== 0"
          src="@/assets/img/arrow_down.png"
          alt=""
          class="w-full transition-all cursor-pointer"
          :class="{
            '-rotate-90': !open,
          }"
          @click="open = !open"
        />
      </div>
      <div
        class="label-text flex-grow overflow-hidden text-ellipsis"
        :title="unit.title"
      >
        {{ unit.title }}
      </div>
      <ElTooltip effect="dark" content="移动" placement="top-start">
        <div class="cursor-move mx-6 moveUnit" ref="moveElRef">
          <img
            src="@/assets/img/move.svg"
            class="select-none"
            draggable="false"
          />
        </div>
      </ElTooltip>
      <ElTooltip effect="dark" content="添加下一级" placement="top-start">
        <div class="cursor-pointer mx-6" @click="addNextlevel(unit)">
          <img src="@/assets/img/addNextLevel.svg" alt="" />
        </div>
      </ElTooltip>
      <ElTooltip effect="dark" content="删除" placement="top-start">
        <div class="cursor-pointer mx-6" @click="del(unit)">
          <img src="@/assets/img/delete.svg" alt="" />
        </div>
      </ElTooltip>
    </h2>
    <div v-show="open">
      <div
        class="propertyContainer"
        v-for="(item, index) in unit.children"
        :key="item.id"
      >
        <div class="px-16 my-8">
          <select-box
            class="property_box property_box-item property_box-item1"
            :class="{
              'half-transparent': startN == index && isInDragging && endN > -1,
            }"
            :select="selectedItem === item"
            @click="emitSelect(item)"
            @del="del"
            :show="3"
            :parent_type="unit.type"
            @addNextlevel="addNextlevel"
            @modifyTitle="modifyTitle"
            @modifyForms="modifyForms"
            @dragstart="dragstart(item, index)"
            @dragend="dragend()"
            @dragover="dragover(item as any, index)"
          >
            <div class="flex-grow relative">
              <div
                class="absolute top-1/2 -translate-y-1/2 -left-8 w-5 h-5"
              ></div>
              <div
                class="blue-line-con"
                v-show="isInDragging && endN === index"
              >
                <div class="blue-line"></div>
              </div>
              <property-item
                class="property-item"
                :property="(item as any)"
                :setProperty="
                  (v) => {
                    changeUnitChildrenItemValue(index, v);
                  }
                "
              ></property-item>
            </div>
          </select-box>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Property, Unit } from "./types2";
import SelectBox from "./SelectBox.vue";
import PropertyItem from "./PropertyItem.vue";
import { defineComponent, PropType } from "vue";
import { ElTooltip } from "element-plus";

export default defineComponent({
  components: {
    SelectBox,
    PropertyItem,
    ElTooltip,
  },
  emits: ["selected", "modifyForms", "modifyTitle", "addNextlevel", "del"],
  inject: ["showTip"],
  props: {
    unit: {
      type: Object as PropType<Unit>,
      required: true,
    },
    setUnit: {
      type: Function,
      required: true,
    },
    selectedItem: {
      type: Object as PropType<Unit | Property | null>,
    },
    setSelectedItem: {
      type: Function as PropType<any>,
    },
    isDisabled: {
      type: Boolean as PropType<boolean>,
    },
    switchPosition: {
      type: Function,
    },
  },
  data() {
    return {
      startN: -1,
      endN: -1,
      isInDragging: false,
      open: true,
      canMove: false,
    };
  },
  methods: {
    changeUnitChildrenItemValue(i: number, v: any) {
      const u = this.unit;
      u.children[i] = v;
      this.setUnit(u);
    },
    emitSelect(item?: Unit | Property) {
      this.$emit("selected", item);
    },
    // 修改表现形式
    modifyForms() {
      let that: any = this.selectedItem;
      if (this.selectedItem && this.selectedItem.type === 3) {
        return false;
      }
      if (this.selectedItem && this.selectedItem.type === 6) {
        if (that.value.trim() !== "") {
          that.value = this.timeFormate(that.value);
          this.setSelectedItem(that);
        }
      }
      this.$emit("modifyForms");
    },
    timeFormate(timestamp: number) {
      let date = new Date(timestamp * 1000);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate() + " ";
      return Y + M + D;
    },
    modifyTitle() {
      this.$emit("modifyTitle");
    },
    addNextlevel(data?: any) {
      this.$emit("addNextlevel", data);
    },
    del(data?: any) {
      if (!data) {
        this.$emit("del", data);
        this.emitSelect();
      } else {
        if (this.unit.children.length !== 0) {
          (this as any).showTip(
            "包含多条表单，删除后会⼀并删除，确定要删除吗？",
            () => {
              this.$emit("del", data);
              this.emitSelect();
            },
            () => {
              //
            }
          );
        } else {
          this.$emit("del", data);
          this.emitSelect();
        }
      }
    },
    dragstart(item: Unit | Property, index: number) {
      this.endN = -1; //执行dragover操作时，start element才进入虚化
      this.startN = index;
      this.isInDragging = true;
    },
    // 拖动结束
    dragend() {
      this.isInDragging = false;
      if (this.startN === this.endN || this.endN < 0) {
        return false;
      } else {
        var Property = this.unit.children[this.startN]; //目标
        // eslint-disable-next-line vue/no-mutating-props
        this.unit.children.splice(this.endN, 0, Property);
        if (this.startN > this.endN) {
          // eslint-disable-next-line vue/no-mutating-props
          this.unit.children.splice(this.startN + 1, 1);
        } else if (this.startN < this.endN) {
          // eslint-disable-next-line vue/no-mutating-props
          this.unit.children.splice(this.startN, 1);
        }
        this.$forceUpdate();
      }
      console.log(this.unit.children);
    },
    // 进入另一个目标元素
    dragover(item: Unit, index: number) {
      this.endN = index;
    },
    dragoverExt(e: any) {
      //
    },
    root_dragstart(ev: any) {
      // if (this.canMove) {
      //   ev.dataTransfer.setData("application/my-app", this.unit.id);
      //   ev.dataTransfer.dropEffect = "move";
      // } else {
      //   ev.preventDefault();
      // }
    },
    root_drop(ev: any) {
      // ev.preventDefault();
      // const unitId = ev.dataTransfer.getData("application/my-app");
      // // console.log(unitId, "show getData in drop");
      // this.unit.id &&
      //   unitId &&
      //   this.switchPosition &&
      //   this.switchPosition(this.unit.id, unitId);
    },
    root_dragend(ev: any) {
      // const unitId = ev.dataTransfer.getData("application/my-app");
      // console.log(unitId, "show getData in dragend");
    },
    root_dragover(ev: any) {
      // ev.preventDefault();
      // ev.dataTransfer.dropEffect = "move";
      // console.log("in dragover");
    },
    handleMouseDown(ev: Event) {
      const target = ev.target as HTMLElement;
      const content = this.$refs.moveElRef as HTMLElement;
      this.canMove = content.contains(target);
    },
  },
});
</script>

<style scoped lang="scss">
.root_unit {
  .show-border-bottom {
    border-bottom: 1px solid #dddddd;
  }
}
.title {
  padding-left: 18px;
  margin: 0;
  line-height: 42px;
  font-size: 16px;
  font-weight: bold;
  color: #292929;
  background: #ffffff;
  height: 58px;
  .label-text {
    line-height: 58px;
  }
}

.title_box {
  width: 100%;
  border-bottom: 1px solid #dddddd;
}

.unit_box {
  width: 1060px; /* todo 选中效果ui未给出 */
  margin-top: 10px;
  padding: 10px 0;
}

.property_box {
  width: 100%;
  padding-right: 20px;
}
.blue-line-con {
  position: relative;
  height: 1px;
}
.blue-line {
  height: 1px;
  background-color: var(--sy-blue);

  width: 300px;
  display: inline-block;

  position: absolute;
  top: 0px;
  left: 50%;
  transform: translate(-50%, 0);
}

.half-transparent {
  opacity: 0.3;
}
</style>

<style lang="scss">
/*
 * 二级hover下，显示item头
 */
/* .propertyContainer:hover .property_box-item1 .base_form:hover .pre-tag,
.propertyContainer:hover .property_box-item1 .image_form:hover .pre-tag,
.propertyContainer:hover .property_box-item1 .title:hover .pre-tag {
  display: block;
} */
/*
 * 被选中的二级item，即使在hover状态下，也不显示item头
 */
/* .propertyContainer:hover
  .property_box-item1.js-select_box_active
  .base_form
  .pre-tag,
.propertyContainer:hover
  .property_box-item1.js-select_box_active
  .image_form
  .pre-tag,
.propertyContainer:hover
  .property_box-item1.js-select_box_active
  .title
  .pre-tag {
  display: none;
} */
/*
 * 即使二级item被选中，对应的三级hover下也显示item头
 */
.propertyContainer:hover .pre-tag,
.propertyContainer:hover
  .property_box-item1
  .property_box-item2
  .base_form
  .pre-tag,
.propertyContainer:hover
  .property_box-item1
  .property_box-item2
  .image_form
  .pre-tag,
.propertyContainer:hover
  .property_box-item1
  .property_box-item2
  .title
  .pre-tag {
  display: block !important;
}
</style>
