import { promisefiyPostMessage } from '@/helpers/native-message';
import html2canvas from 'html2canvas';
import {
  closeToast,
  showFailToast,
  showLoadingToast,
  showSuccessToast
} from 'vant';
import {
  defineComponent,
  toRefs,
  ref,
  reactive,
  onMounted,
  onUnmounted,
  nextTick
} from 'vue';
import styles from './pen.module.less';
import Tips, { tipState } from '../tips';

export default defineComponent({
  name: 'tools-pen',
  props: {
    isWhite: {
      type: Boolean,
      default: false
    },
    tip: {
      type: String,
      default: '请确认是否退出？'
    },
    show: {
      type: Boolean,
      default: false
    },
    close: {
      type: Function,
      default: () => ({})
    }
  },
  setup(props) {
    const { show } = toRefs(props);
    const firstRender = ref(true);
    const src = /(localhost|192)/.test(location.host)
      ? 'https://test.lexiaoya.cn/whiteboard-noCollab'
      : `https://online.lexiaoya.cn/whiteboard-noCollab`;

    const exportImg = (event: MessageEvent) => {
      const data = event.data;
      // console.log('🚀 ~ event:', data)
      if (data.api === 'excalidraw_exportImg') {
        imgs.base64 = data.base64;
        imgs.exported = true;
        nextTick(() => {
          onSaveImg();
        });
      }
    };
    onMounted(() => {
      window.addEventListener('message', exportImg);
    });
    onUnmounted(() => {
      window.removeEventListener('message', exportImg);
    });

    const imgs = reactive({
      exported: false,
      saveLoading: false,
      base64: '',
      image: ''
    });

    const saveImg = async () => {
      showLoadingToast({ message: '图片生成中...', forbidClick: true });
      setTimeout(() => {
        imgs.saveLoading = false;
      }, 100);
      const res = await promisefiyPostMessage({
        api: 'savePicture',
        content: {
          base64: imgs.image
        }
      });
      if (res?.content?.status === 'success') {
        showSuccessToast('保存成功');
      } else {
        showFailToast('保存失败');
      }
      imgs.exported = false;
    };

    const onSaveImg = async () => {
      // 判断是否在保存中...
      if (imgs.saveLoading) {
        return;
      }
      console.log('开始');
      imgs.saveLoading = true;
      const container: any = document.getElementById(`app`);
      html2canvas(container, {
        allowTaint: true,
        useCORS: true,
        backgroundColor: null
      })
        .then(async canvas => {
          // console.log("🚀 ~ canvas:", canvas)
          // document.body.appendChild(canvas)
          // const url = await canvas.toDataURL()
          try {
            imgs.image = canvas.toDataURL();
          } catch (error) {
            console.log(error);
          }
          console.log('🚀 ~ imgs.image:', imgs.image);
          saveImg();
        })
        .catch(error => {
          console.log('🚀 ~ error:', error);
          closeToast();
          imgs.saveLoading = false;
          imgs.exported = false;
        });
    };

    return () => (
      <div
        class={[
          styles.pen,
          firstRender.value ? styles.dely : '',
          show.value ? styles.open : styles.hide
        ]}>
        <iframe
          class={styles.iframe}
          style={{
            background: props.isWhite ? '#fff' : 'transparent'
          }}
          frameborder="0"
          width="100vw"
          height="100vh"
          src={src}
          onLoad={() => {
            firstRender.value = false;
          }}></iframe>
        {imgs.exported ? (
          <img crossorigin="anonymous" class={styles.img} src={imgs.base64} />
        ) : (
          <div class={styles.rightItem} onClick={() => {
            tipState.content = props.tip
            tipState.show = true
          }}>
            <svg width="22px" height="20px" viewBox="0 0 22 20">
              <path
                transform="translate(-1.000000, -2.000000)"
                fill="#FFFFFF"
                d="M13,2 C13.5522847,2 14,2.44771525 14,3 C14,3.51283584 13.6139598,3.93550716 13.1166211,3.99327227 L13,4 L3,4 L3,20 L13,20 C13.5128358,20 13.9355072,20.3860402 13.9932723,20.8833789 L14,21 C14,21.5128358 13.6139598,21.9355072 13.1166211,21.9932723 L13,22 L2,22 C1.48716416,22 1.06449284,21.6139598 1.00672773,21.1166211 L1,21 L1,3 C1,2.48716416 1.38604019,2.06449284 1.88337887,2.00672773 L2,2 L13,2 Z M17.7071068,7.05025253 L21.9497475,11.2928932 L21.9497475,11.2928932 C22.3402718,11.6834175 22.3402718,12.3165825 21.9497475,12.7071068 L17.7071068,16.9497475 C17.3165825,17.3402718 16.6834175,17.3402718 16.2928932,16.9497475 C15.9023689,16.5592232 15.9023689,15.9260582 16.2928932,15.5355339 L18.828,12.999 L9.29368112,13 C8.74139637,13 8.29368112,12.5522847 8.29368112,12 C8.29368112,11.4871642 8.67972131,11.0644928 9.17706,11.0067277 L9.29368112,11 L18.827,10.999 L16.2928932,8.46446609 C15.9023689,8.0739418 15.9023689,7.44077682 16.2928932,7.05025253 C16.6834175,6.65972824 17.3165825,6.65972824 17.7071068,7.05025253 Z"></path>
            </svg>
          </div>
        )}

        <Tips onConfirm={() => {
          props.close()
          tipState.show = false
        }} />
      </div>
    );
  }
});
