<template>
  <div class="house-layout">
    <div class="iframe-layout">
      <iframe :src="fuseUrl" ref="iframeRef" />
    </div>
    <div class="content-layout">
      <div class="house-tags">
        <h4>请选择要同步到现场图的标注：</h4>
        <div
          class="tagging-transfer"
          v-sortable="{ handle: '.value-option' }"
          ref="dragLayout"
        >
          <el-transfer
            :titles="['所有', '需要']"
            v-model="transferValue"
            :data="transferSource"
            target-order="push"
          >
            <template #default="{ option }">
              <span
                :class="{ 'value-option': transferValue.includes(option.key) }"
                :id="'o' + option.key"
                :draggable="transferValue.includes(option.key)"
              >
                <span>{{ option.label }}</span>
                <el-icon v-if="transferValue.includes(option.key)"><Rank /></el-icon>
              </span>
            </template>
          </el-transfer>
        </div>
      </div>
      <div class="house-image-layout">
        <h4>
          户型图：
          <el-icon><Refresh class="icon" @click="refreshBlob" /></el-icon>
        </h4>
        <div class="house-image">
          <div>
            <img :src="coverUrl" v-if="coverUrl" />
            <el-empty description="暂无数据" v-else />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { CaseTagging, getCaseTaggings } from "@/store/caseTagging";
import {
  getFuseImage,
  getQuery,
  FuseImageType,
  fuseImageJoinHot,
  fuseIframeHandler,
} from "@/view/case/help";
import { computed, nextTick, onMounted, ref, watchEffect } from "vue";
import { QuiskExpose } from "@/helper/mount";
import { imageCropper } from "@/view/system/quisk";

export type FuseImage = { blob: Blob | null; taggings: CaseTagging[] };
const props = defineProps<{ caseId: number }>();

const fuseUrl = computed(() => getQuery(props.caseId, true, true));

const taggings = ref<CaseTagging[]>([]);
const transferSource = computed(() =>
  taggings.value.map((item) => ({
    key: item.tagId,
    data: item,
    label: item.tagTitle,
  }))
);
const transferValue = ref<number[]>([]);
const selectTaggings = computed(() =>
  transferValue.value.map((tagId) => taggings.value.find((tag) => tag.tagId === tagId)!)
);

const iframeRef = ref<HTMLIFrameElement>();
const imageBlob = ref<Blob | null>(null);
const coverUrl = computed(() => imageBlob.value && URL.createObjectURL(imageBlob.value));

watchEffect((onClanup) => {
  if (iframeRef.value) {
    onClanup(fuseIframeHandler(iframeRef.value));
  }
});

const refreshBlob = async () => {
  if (!iframeRef.value) {
    return;
  }
  const scale = 1.564;
  const width = Math.ceil(540 * scale);
  const height = Math.ceil(390 * scale);
  const fuseImage = await getFuseImage(iframeRef.value, width, height);

  if (fuseImage?.blob) {
    console.log('fuseImage', fuseImage?.blob);
    const cropBlob = await imageCropper({
      img: fuseImage?.blob,
      fixed: [width, height]
     })
    imageBlob.value =
      fuseImage.type !== FuseImageType.FUSE
        ? cropBlob
        : await fuseImageJoinHot(
            iframeRef.value,
            cropBlob,
            selectTaggings.value,
            width,
            height,
            scale
          );
  }
};

defineExpose<QuiskExpose>({
  submit() {
    return { blob: imageBlob.value, taggings: selectTaggings.value };
  },
});

onMounted(async () => {
  taggings.value = await getCaseTaggings(props.caseId);
});

watchEffect(async (onClanup) => {
  transferValue.value.join("");
  await nextTick();
  const desps: (() => void)[] = [];
  let repKey: number | null;
  for (const key of transferValue.value) {
    const $option = document.querySelector("#o" + key) as HTMLDivElement;
    const startHandler = () => {
      $option.classList.add("dragging");
      repKey = key;

      $option.addEventListener("dragend", function endHandler(ev) {
        $option.classList.remove("dragging");
        $option.removeEventListener("dragend", endHandler);
      });
    };
    const dragoverHandler = (ev: Event) => ev.preventDefault();
    const dropHandler = (ev: Event) => {
      ev.preventDefault();
      if (repKey && key !== repKey) {
        const oldIndex = transferValue.value.indexOf(key);
        const newIndex = transferValue.value.indexOf(repKey);
        transferValue.value[newIndex] = key;
        transferValue.value[oldIndex] = repKey;
      }
    };

    $option.addEventListener("dragstart", startHandler);
    $option.addEventListener("dragover", dragoverHandler);
    $option.addEventListener("drop", dropHandler);

    desps.push(() => {
      $option.removeEventListener("dragstart", startHandler);
      $option.removeEventListener("dragover", startHandler);
      $option.removeEventListener("drop", dropHandler);
    });
  }

  onClanup(() => {
    desps.forEach((desp) => desp());
  });
});
</script>

<style lang="scss" scoped>
.house-layout {
  --w: calc(540 / 390 * var(--h));
  --h: 610px;
  display: flex;
  height: var(--h);
}

.iframe-layout {
  height: 100%;
  flex: 0 0 var(--w);
  display: flex;
  align-items: center;
  iframe {
    border: none;
    width: 100%;
    height: var(--h);
  }
}

.content-layout {
  flex: none;
  width: 360px;
  display: flex;
  flex-direction: column;
  margin-left: 40px;
  height: 100%;
  justify-content: space-between;

  h4 {
    font-size: 14px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    line-height: 22px;
    margin-bottom: 15px;
    flex: none;

    span {
      float: right;
    }
  }

  > .house-tags {
    flex: none;
    display: flex;
    flex-direction: column;

    > .tagging-transfer {
      flex: 1;
      overflow: hidden;
    }
  }
}
.house-image {
  border: 1px solid #d9d9d9;
  padding-top: 68%;
  position: relative;

  > div {
    position: absolute;
    inset: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
</style>

<style lang="scss">
.tagging-transfer {
  .el-transfer {
    display: flex;
    --el-transfer-panel-body-height: 160px;
  }
  .el-transfer__buttons {
    padding: 0 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    button {
      padding: 0;
      width: 24px;
      height: 24px;
      display: block;
      margin: 5px 0;
    }
  }
  .el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label {
    font-size: 14px;
  }
}
.icon {
  cursor: pointer;
}

.value-option {
  display: flex;
  align-items: center;

  span {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  i {
    flex: 0 0 auto;
  }
}
</style>

<style>
.value-option.dragging {
  opacity: 0.5;
}
</style>
