<template>
    <div class="header">
        <van-button color="dimgray" @click="$router.back()" type="default" size="small">返回</van-button>
        <van-uploader :after-read="afterRead" :before-read="beforeRead" accept="image/*" :max-size="10 * 1024 * 1024"
                      @oversize="onOversize">
            <van-button icon="plus" size="small" type="primary">上传文件</van-button>
        </van-uploader>
        <van-button type="success" @click="save" size="small">保存</van-button>
    </div>
    <div id="tui-image-editor" class="tui-image-editor"></div>
</template>

<script lang="ts">
import {onMounted, onBeforeUnmount, ref, defineComponent, getCurrentInstance} from "vue";
import 'tui-image-editor/dist/tui-image-editor.min.css';
import ImageEditor from "tui-image-editor"
import {UpyunAccess, hwUpYun} from "~/utils/upyun";
import {showFailToast, showSuccessToast, Button, Uploader} from "vant";
import usePool from "~/store/pool";
import useLoading from "~/store/loading";
import {ImageHelper} from "~/utils";

const WhiteTheme = {
    'common.bi.image': 'https://uicdn.toast.com/toastui/img/tui-image-editor-bi.png',
    'common.bisize.width': '251px',
    'common.bisize.height': '21px',
    'common.backgroundImage': 'none',
    'common.backgroundColor': '#fff',
    'common.border': 'none',

    // header
    'header.backgroundImage': 'none',
    'header.backgroundColor': '#000',
    'header.border': '0px',

    // load button
    'loadButton.backgroundColor': '#fff',
    'loadButton.border': '1px solid #ddd',
    'loadButton.color': '#222',
    'loadButton.fontFamily': "'Noto Sans', sans-serif",
    'loadButton.fontSize': '12px',
    'loadButton.display': 'none',

    // download button
    'downloadButton.backgroundColor': '#fdba3b',
    'downloadButton.border': '1px solid #fdba3b',
    'downloadButton.color': '#fff',
    'downloadButton.fontFamily': "'Noto Sans', sans-serif",
    'downloadButton.fontSize': '12px',
    'downloadButton.display': 'none',

    // main icons
    'menu.normalIcon.color': '#8a8a8a',
    'menu.activeIcon.color': '#555555',
    'menu.disabledIcon.color': '#434343',
    'menu.hoverIcon.color': '#e9e9e9',
    'menu.iconSize.width': '24px',
    'menu.iconSize.height': '24px',

    // submenu icons
    'submenu.normalIcon.color': '#8a8a8a',
    'submenu.activeIcon.color': '#555555',
    'submenu.iconSize.width': '24px',
    'submenu.iconSize.height': '24px',

    // submenu primary color
    'submenu.backgroundColor': 'transparent',
    'submenu.partition.color': '#e5e5e5',

    // submenu labels
    'submenu.normalLabel.color': '#858585',
    'submenu.normalLabel.fontWeight': 'normal',
    'submenu.activeLabel.color': '#000',
    'submenu.activeLabel.fontWeight': 'normal',

    // checkbox style
    'checkbox.border': '1px solid #ccc',
    'checkbox.backgroundColor': '#fff',

    // rango style
    'range.pointer.color': '#333',
    'range.bar.color': '#ccc',
    'range.subbar.color': '#606060',

    'range.disabledPointer.color': '#d3d3d3',
    'range.disabledBar.color': 'rgba(85,85,85,0.06)',
    'range.disabledSubbar.color': 'rgba(51,51,51,0.2)',

    'range.value.color': '#000',
    'range.value.fontWeight': 'normal',
    'range.value.fontSize': '11px',
    'range.value.border': '0',
    'range.value.backgroundColor': '#f5f5f5',
    'range.title.color': '#000',
    'range.title.fontWeight': 'lighter',

    // colorpicker style
    'colorpicker.button.border': '0px',
    'colorpicker.title.color': '#000',
};

const BlackTheme = {
    'common.bi.image': 'https://uicdn.toast.com/toastui/img/tui-image-editor-bi.png',
    'common.bisize.width': '251px',
    'common.bisize.height': '21px',
    'common.backgroundImage': 'none',
    'common.backgroundColor': '#1e1e1e',
    'common.border': '0px',

    // header
    'header.backgroundImage': 'none',
    'header.backgroundColor': 'transparent',
    'header.border': '0px',

    // load button
    'loadButton.backgroundColor': '#fff',
    'loadButton.border': '1px solid #ddd',
    'loadButton.color': '#222',
    'loadButton.fontFamily': "'Noto Sans', sans-serif",
    'loadButton.fontSize': '12px',
    'loadButton.display': 'none',

    // download button
    'downloadButton.backgroundColor': '#fdba3b',
    'downloadButton.border': '1px solid #fdba3b',
    'downloadButton.color': '#fff',
    'downloadButton.fontFamily': "'Noto Sans', sans-serif",
    'downloadButton.fontSize': '12px',
    'downloadButton.display': 'none',

    // main icons
    'menu.normalIcon.color': '#8a8a8a',
    'menu.activeIcon.color': '#555555',
    'menu.disabledIcon.color': '#434343',
    'menu.hoverIcon.color': '#e9e9e9',
    'menu.iconSize.width': '24px',
    'menu.iconSize.height': '24px',

    // submenu icons
    'submenu.normalIcon.color': '#8a8a8a',
    'submenu.activeIcon.color': '#e9e9e9',
    'submenu.iconSize.width': '24px',
    'submenu.iconSize.height': '24px',

    // submenu primary color
    'submenu.backgroundColor': '#1e1e1e',
    'submenu.partition.color': '#3c3c3c',

    // submenu labels
    'submenu.normalLabel.color': '#8a8a8a',
    'submenu.normalLabel.fontWeight': 'lighter',
    'submenu.activeLabel.color': '#fff',
    'submenu.activeLabel.fontWeight': 'lighter',

    // checkbox style
    'checkbox.border': '0px',
    'checkbox.backgroundColor': '#fff',

    // range style
    'range.pointer.color': '#fff',
    'range.bar.color': '#666',
    'range.subbar.color': '#d1d1d1',

    'range.disabledPointer.color': '#414141',
    'range.disabledBar.color': '#282828',
    'range.disabledSubbar.color': '#414141',

    'range.value.color': '#fff',
    'range.value.fontWeight': 'lighter',
    'range.value.fontSize': '11px',
    'range.value.border': '1px solid #353535',
    'range.value.backgroundColor': '#151515',
    'range.title.color': '#fff',
    'range.title.fontWeight': 'lighter',

    // colorpicker style
    'colorpicker.button.border': '1px solid #1e1e1e',
    'colorpicker.title.color': '#fff',
};
const LOCALE = {
    "Apply": "确定",
    "Arrow": "箭头",
    "Arrow-2": "箭头-2",
    "Arrow-3": "箭头-3",
    "Blend": "",
    "Blur": "模糊",
    "Bold": "粗体",
    "Brightness": "亮度",
    "Bubble": "气泡",
    "Cancel": "取消",
    "Center": "中心",
    "Circle": "圆",
    "Color": "颜色",
    "Color Filter": "颜色过滤",
    "Crop": "裁剪",
    "Custom": "自定义",
    "Custom icon": "自定义图标",
    "Delete": "删除",
    "Delete-all": "删除全部",
    "Distance": "距离",
    "Download": "保存",
    "Draw": "绘画",
    "Emboss": "浮雕",
    "Fill": "填充",
    "Filter": "",
    "Flip": "翻转",
    "Flip X": "水平翻转",
    "Flip Y": "垂直翻转",
    "Free": "",
    "Grayscale": "灰度",
    "Heart": "爱心",
    "History": "历史",
    "Icon": "图标",
    "Invert": "反色",
    "Italic": "斜体",
    "Left": "左",
    "Load": "上传",
    "Load Mask Image": "加载遮罩图",
    "Location": "定位",
    "Mask": "遮罩",
    "Multiply": "翻倍",
    "Noise": "噪点",
    "Pixelate": "像素化",
    "Polygon": "多边形",
    "Range": "Range",
    "Rectangle": "矩形",
    "Redo": "重做",
    "Remove White": "移除白色",
    "Reset": "重置",
    "Right": "右",
    "Rotate": "旋转",
    "Sepia": "颜料",
    "Sepia2": "颜料2",
    "Shape": "形状",
    "Sharpen": "锐度",
    "Square": "方形",
    "Star-1": "星-1",
    "Star-2": "星-2",
    "Straight": "直线",
    "Stroke": "颜色",
    "Text": "文字",
    "Text size": "文字尺寸",
    "Threshold": "",
    "Tint": "着色",
    "Triangle": "三角形",
    "Underline": "下划线",
    "Undo": "撤销",
    "Value": "值",
    "ZoomIn": "放大",
    "ZoomOut": "缩小"
}

export default defineComponent({
    name: "photo-editor",
    props: {
        url: {type: String},
        theme: {type: String, default: "black"}
    },
    emits: ["save"],
    components: {
        [Button.name]: Button,
        [Uploader.name]: Uploader
    },
    setup({url, theme}) {

        usePool().set({hide_bottom_tab: true})
        const editor = ref<ImageEditor | null>(null)
        const instance = getCurrentInstance();
        const {load_start, load_done} = useLoading()
        const fileList = ref([])

        onMounted(async () => {

            let initial = {};
            if (url) {
                let path = url;
                if (url.includes("upyun")) {
                    path = await UpyunAccess.getSign(url) as string
                    path += "&t=" + Date.now() // to avoid CORS issue
                }
                initial = {loadImage: {path, name: "avatar"}}
            }

            editor.value = new ImageEditor("#tui-image-editor", {
                includeUI: {
                    ...initial,
                    // @ts-ignore
                    locale: LOCALE,
                    theme: {"black": BlackTheme, "white": WhiteTheme}[theme] || BlackTheme,
                    initMenu: 'crop',
                    menuBarPosition: 'bottom',
                    uiSize: {
                        width: '100%',
                        height: 'calc(100% - 40px)'
                    }
                },
                cssMaxWidth: document.documentElement.clientWidth,
                cssMaxHeight: document.documentElement.clientHeight - 40,
                selectionStyle: {
                    cornerSize: 50,
                    rotatingPointOffset: 100,
                },
            })
        })

        onBeforeUnmount(() => {
            usePool().set({hide_bottom_tab: false})
            load_done();
            if (editor.value) {
                editor.value.destroy();
            }
        })

        const save = async () => {
            load_start()
            let inst = editor.value as ImageEditor;
            let base64 = inst.toDataURL({format: 'jpeg', quality: 1});
            let blob = await (await fetch(base64)).blob();
            let file = new File([blob], "avatar.jpeg")
            let url = await ImageHelper.compress_by_form(file)
            if (url) {
                showSuccessToast("文件保存成功！");
                instance?.emit("save", url);
            }
            load_done()
        }

        const beforeRead = (file) => {
            if (!file.type.startsWith("image")) {
                showFailToast('请上传图片文件！');
                return false;
            }
            return true;
        };

        const afterRead = (file: any) => {
            let inst = editor.value as ImageEditor;
            inst.loadImageFromFile(file.file)
        }
        const onOversize = (file: File) => {
            showFailToast('文件大小不能超过10MB!');
        };

        return {fileList, afterRead, save, beforeRead, onOversize}

    }
})


</script>

<style scoped lang="less">

.header {
  height: 40px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #1e1e1e;

  > button {
    width: 30%;
  }

  :deep(.van-uploader) {
    width: 30%;
  }
}

.tui-image-editor-container {

  .tui-image-editor-header-logo {
    display: none;
  }

  .tui-image-editor-header-buttons {
    div, button {
      width: auto;
      height: auto;
      padding: 3px 5px;
      line-height: unset;
      border-radius: 2px;
    }

  }

  .tui-image-editor-header {
    min-width: 375px;
    top: 8px;
  }

  .tui-image-editor-help-menu.top {
    border-radius: 0;
    height: 36px;
    line-height: 36px;
    width: 100%;

    .tui-image-editor-icpartition {
      height: 16px;
    }
  }

  .svg_ic-menu, .svg_ic-submenu, .svg_ic-helpmenu {

  }

  .tui-image-editor-controls {

    .tui-image-editor-menu {

      > .tui-image-editor-item {

        padding: 5px 4px 2px;
        margin: 0 2px;

      }
    }

  }

  .tui-image-editor-help-menu {

    width: 306px;

    > .tui-image-editor-item {
      padding: 5px 4px 2px;
      margin: 0 2px;
    }
  }

  .tui-image-editor-submenu .tui-image-editor-submenu-item .action .tui-image-editor-button {
    display: inline-flex;
    align-items: center;
  }

  .tui-image-editor-header-buttons {
    float: none;
    margin: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 36px;
    padding: 0 5px;
  }
}


</style>
