<script setup>
import ImageEditor from "tui-image-editor";
import "tui-color-picker/dist/tui-color-picker.css";
import "tui-image-editor/dist/tui-image-editor.css";
import { computed } from "vue";
import { debounce } from "lodash-es";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  src: {
    type: String,
    default: "",
  },
  data: {
    type: Object,
    default: () => ({}),
  },
});
const emits = defineEmits(["update:modelValue", "onSave"]);

const isShow = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  },
});
const activeNav = ref();
const nav = ref([]);
function clickNav(i) {
  activeNav.value = i;
  init(i.url);
}
// 中文菜单
const localeCN = {
  Crop: "裁剪",
  Draw: "涂鸦",
  Text: "添加文本",
  Free: "任意线条",
  Straight: "直线",
  Icon: "添加图标",
  Color: "颜色",
  Range: "范围",
  Undo: "上一步",
  Redo: "下一步",
  Reset: "重置",
  Delete: "删除",
  ZoomOut: "缩小",
  ZoomIn: "放大",
  Width: "宽",
  Height: "高",
  Apply: "应用",
  Cancel: "取消",
  "Lock Aspect Ratio": "锁定比例",
  Bold: "加粗",
  Italic: "斜体",
  Underline: "下划线",
  Left: "左对齐",
  Center: "居中",
  Right: "右对齐",
};
const customTheme = {
  // "common.backgroundColor": "#fff",
  // "header.backgroundColor": "#000",
};

let instance;
const isModified = ref(false);
function init(path) {
  instance = new ImageEditor(document.querySelector("#tui-image-editor"), {
    includeUI: {
      loadImage: {
        path,
        name: "image",
      },
      initMenu: "draw", // 默认打开的菜单项
      // menuBarPosition: 'bottom', // 菜单所在的位置
      menu: [
        // "free",
        "resize", // 放大
        // "crop", // 裁切
        "draw", // 添加绘画
        "text", // 添加文本
        // 'rotate', // 旋转
        // 'flip', // 翻转
        // 'shape', // 添加形状
        // 'icon', // 添加图标
        // 'mask', // 添加覆盖
        // 'filter' // 添加滤镜
      ],
      // 汉化
      locale: localeCN,
      theme: customTheme,
    },
    cssMaxWidth: 1000, // canvas 最大宽度
    cssMaxHeight: 1000, // canvas 最大高度
  });

  instance.on("objectAdded", () => {
    isModified.value = true;
  });

  instance.on("objectModified", () => {
    isModified.value = true;
  });

  instance.on("undoStackChanged", () => {
    isModified.value = !instance.isEmptyUndoStack();
  });

  instance.on("redoStackChanged", () => {
    isModified.value = !instance.isEmptyUndoStack();
  });

  // document.getElementsByClassName('tui-image-editor-wrap')[0].style.bottom = 90

  document.querySelector(".tui-image-editor-header").style.display = "none";

  //! 修改图片编辑器的顶部导航栏
  document.querySelector('[tooltip-content="History"]').style.display = "none";
  // document.querySelector('[tooltip-content="Undo"]').style.display = 'none' // 上一步
  // document.querySelector('[tooltip-content="Redo"]').style.display = 'none' // 下一步
  // document.querySelector('[tooltip-content="Reset"]').style.display = 'none' // 完全重新编辑
  // document.querySelector('[tooltip-content="Delete"]').style.display = 'none'
  document.querySelector('[tooltip-content="DeleteAll"]').style.display =
    "none";
  document.querySelector('[tooltip-content="Hand"]').style.display = "none";
  // document.querySelector('[tooltip-content="ZoomOut"]').style.display = "none";
  // document.querySelector('[tooltip-content="ZoomIn"]').style.display = "none";
}

// base64转为blob
function dataURLtoBlob() {
  const dataUrl = instance.toDataURL();
  var arr = dataUrl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

const loading = ref(false);
// 保存图片到本地
function _handleSave() {
  loading.value = true;
  try {
    const file = dataURLtoBlob();
    emits("onSave", file, props.data);
    isShow.value = false;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}

const handleSave = debounce(_handleSave, 1000, {
  leading: true,
  trailing: false,
});

function handleOpen() {
  init(props.src);
  if (props.data.markUrl) {
    nav.value = [
      {
        name: "原图",
        type: 0,
        url: props.data.submitUrl,
      },
      { name: "批改图", type: 1, url: props.data.markUrl },
    ];
  } else {
    nav.value = [
      {
        name: "原图",
        type: 0,
        url: props.data.submitUrl,
      },
    ];
  }
  activeNav.value = nav.value[0];
}
</script>
<template>
  <el-dialog
    fullscreen
    append-to-body
    v-model="isShow"
    class="imageEditDia"
    align-center
    @open="handleOpen"
  >
    <template #header>
      <div class="nav">
        <span
          :class="{ nav_item: true, active: i.type === activeNav.type }"
          v-for="i in nav"
          :key="i.type"
          @click="clickNav(i)"
          >{{ i.name }}</span
        >
      </div>
    </template>
    <div class="image-box">
      <div id="tui-image-editor"></div>
    </div>
    <template #footer>
      <el-button
        type="primary"
        :loading="loading"
        :disabled="!isModified"
        @click="handleSave"
        >保存</el-button
      >
    </template>
  </el-dialog>
</template>
<style lang="scss">
.imageEditDia {
  .el-dialog__header {
    padding-bottom: 0;
  }
  .el-dialog__body {
    height: calc(100% - 100px);
  }
  .el-dialog__footer {
    padding-bottom: 12px;
  }
}
.tui-image-editor-help-menu {
  display: none;
}
.nav {
  display: flex;
  justify-content: center;
  &_item {
    display: inline-block;
    padding: 4px 8px;
    font-size: 18px;
    color: #fff;
    background-color: #75bd42;
    border: 1px solid #fff;
    &:hover {
      cursor: pointer;
    }
  }
  .active {
    background-color: #ee822f;
  }
}
.image-box {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}
</style>
