import { defineComponent, reactive, ref, watch } from 'vue'
import styles from './download.module.less'
import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
import {
  addMusicTitle,
  addWatermark,
  convasToImg,
  imgToCanvas
} from './imageFunction'
import { Button, Swipe, SwipeItem, Toast, Image } from 'vant'

export default defineComponent({
  name: 'download',
  props: {
    imgList: {
      type: Array,
      default: () => []
    },
    musicSheetName: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const list = ref(props.imgList)
    const swipeRef = ref()
    watch(
      () => props.imgList,
      (val: any) => {
        list.value = val
        acitveIndex.value = 0
        if (swipeRef.value) swipeRef.value.swipeTo(0)
      }
    )
    const acitveIndex = ref(0)
    const saveLoading = ref<boolean>(false)
    const image = ref('')
    const onSaveImg = async () => {
      // 判断是否在保存中...
      if (saveLoading.value) {
        return
      }
      saveLoading.value = true
      // 判断是否已经生成图片
      if (image.value) {
        saveImg()
      } else {
        console.log(
          list.value[acitveIndex.value],
          'list.value[acitveIndex.value]'
        )
        const tempCanvas = await imgToCanvas(
          list.value[acitveIndex.value] as any
        )
        const titleCanvas = addMusicTitle(tempCanvas, {
          title: props.musicSheetName,
          size: 18
        })
        const canvas = await addWatermark(titleCanvas, '酷乐秀')
        image.value = convasToImg(canvas)
        console.log(image.value, 'image.value')
        await saveImg()
      }
    }

    const saveImg = async () => {
      Toast.loading({
        message: '图片生成中...',
        forbidClick: true
      })
      setTimeout(() => {
        saveLoading.value = false
      }, 100)
      const res = await promisefiyPostMessage({
        api: 'savePicture',
        content: {
          base64: image.value
        }
      })
      if (res?.content?.status === 'success') {
        Toast.success('已保存到相册')
      } else {
        Toast.fail('保存失败')
      }
    }
    return () => {
      return (
        <div class={styles.downloadContainer}>
          <div class={styles.musicContainer}>
            <h2>{props.musicSheetName}</h2>
            <div class={styles.musicImg}>
              <Swipe
                ref={swipeRef}
                showIndicators={false}
                loop={false}
                onChange={(index: number) => {
                  acitveIndex.value = index
                  image.value = ''
                }}
              >
                {list.value.length > 0 &&
                  list.value.map((img: any) => (
                    <SwipeItem>
                      <Image src={img} />
                    </SwipeItem>
                  ))}
              </Swipe>
            </div>
          </div>
          <div class={styles.buttonGroup}>
            <div class={styles.num}>
              <span class={styles.page}>
                {acitveIndex.value + 1}/{list.value.length}
              </span>
              <span class={styles.countPage}>（共{list.value.length}页）</span>
            </div>

            <Button
              type="primary"
              color="linear-gradient(270deg, #FF204B 0%, #FE5B71 100%)"
              class={styles.downloadBtn}
              block
              round
              onClick={() => onSaveImg()}
              loading={saveLoading.value}
              loadingText={'加载中...'}
            >
              下载当前页面
            </Button>
          </div>
        </div>
      )
    }
  }
})
