import { defineComponent, onMounted, onUnmounted, reactive } from 'vue'
import styles from './index.module.less'
import { api_uploadFile } from '@/plugins/uploadFile'
import { useMessage } from 'naive-ui'

export default defineComponent({
  name: 'music-create-img',
  props: {
    xmlFileUrl: {
      type: String,
      default: ''
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const message = useMessage()
    const state = reactive({
      productOpen: false,
      productIfameSrc: ''
    })
    /** 自动生成图片 */
    const forms = reactive({
      musicImg: '', // 五线谱图片
      musicFirstImg: '', //首调图片
      musicJianImg: '' // 简谱固定调
    })
    const handleAutoProduct = () => {
      if (!props.xmlFileUrl) {
        message.error('请先上传XML')
        return
      }
      const apiUrls = {
        dev: 'https://dev.kt.colexiu.com',
        test: 'https://test.lexiaoya.cn',
        online: 'https://mec.colexiu.com'
      }

      const environment = location.origin.includes('//dev')
        ? 'dev'
        : location.origin.includes('//test')
        ? 'test'
        : location.origin.includes('//mec')
        ? 'online'
        : 'dev'
      const apiUrl = apiUrls[environment]
      const prefix = /(localhost|192)/.test(location.host) ? 'https://dev.kt.colexiu.com' : apiUrl
      const xmlFileUrl = encodeURIComponent(props.xmlFileUrl)
      state.productIfameSrc =
        prefix + `/instrument/#/product-img?xmlUrl=${xmlFileUrl}&isCreateImg=true&isCbs=true`
      // state.productOpen = true
    }
    const handleProductResult = (res: MessageEvent) => {
      const data = res.data
      if (data?.api === 'webApi_renderSvg') {
        let imgs: any = []
        try {
          imgs = JSON.parse(data.product)
        } catch (error) {
          console.log('🚀 ~ error:', error)
        }
        imgs = imgs.filter((item: any) => item.base64)
        if (imgs.length === 3) {
          message.success('图片生成成功')
          handleUploadImg(imgs)
        } else {
          message.error('图片生成失败')
        }
        // console.log('🚀 ~ 上传之前', [...imgs])
      }
    }
    const handleUploadImg = async (imgs: any[]) => {
      for (let i = 0; i < imgs.length; i++) {
        const file = dataURLtoFile(imgs[i].base64, `${Date.now()}p${i}.png`)
        imgs[i].url = await api_uploadFile(file, () => {})
      }
      forms.musicImg = imgs[0]?.url || ''
      forms.musicFirstImg = imgs[1]?.url || ''
      forms.musicJianImg = imgs[2]?.url || ''
      // state.productOpen = false
      imgs = []

      emit('close')
      emit('confirm', forms)
    }
    /** base64转file */
    const dataURLtoFile = (dataurl: string, filename: string) => {
      let 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 File([u8arr], filename, { type: mime })
    }

    onMounted(() => {
      handleAutoProduct()
      window.addEventListener('message', handleProductResult)
    })

    onUnmounted(() => {
      window.removeEventListener('message', handleProductResult)
    })
    return () => <iframe class={styles.productIframe} src={state.productIfameSrc}></iframe>
  }
})
