import OEmpty from '@/components/o-empty'
import OHeader from '@/components/o-header'
import request from '@/helpers/request'
import { state } from '@/state'
import {
  Grid,
  GridItem,
  Image,
  ImagePreview,
  ImagePreviewInstance,
  List,
  Loading,
  showFailToast,
  showImagePreview,
  showLoadingToast,
  showSuccessToast
} from 'vant'
import { computed, defineComponent, onMounted, reactive, TransitionGroup, ref, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import styles from './index.module.less'
import iconImage from '../images/icon-photo-default.png'
import OSticky from '@/components/o-sticky'
import OFullRefresh from '@/components/o-full-refresh'
import OImage from '@/components/o-image'
import iconDown from '../images/icon-down.png'
import { promisefiyPostMessage } from '@/helpers/native-message'
import html2canvas from 'html2canvas'
export default defineComponent({
  name: 'photo-detail',
  props: {
    orchestraId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const route = useRoute()
    console.log('🚀 ~ route', route)
    const data = reactive({
      downLoading: false,
      downIndex: 0,
      refreshing: false,
      loading: false,
      finished: false,
      pages: {
        page: 1,
        rows: 20
      },
      list: [] as any[],
      startPosition: 0,
      imgShow: false
    })

    const getList = async () => {
      if (data.loading) return
      data.loading = true
      if (data.refreshing) {
        data.list = []
        data.pages.page = 1
      }
      try {
        const res = await request.post(`${state.platformApi}/orchestraPhoto/page`, {
          data: {
            ...data.pages,
            orchestraPhotoAlbumId: route.query.photoId
          }
        })
        if (Array.isArray(res?.data?.rows)) {
          data.list = data.list.concat(res.data.rows)
          data.pages.page = res.data.current + 1
          data.finished = !res.data.next
        } else {
          data.finished = true
        }
      } catch {
        data.finished = true
      }
      data.refreshing = false
      data.loading = false
    }

    // 图片列表
    const images = computed(() => {
      return data.list.map((file: any) => {
        return file.fileUrl
      })
    })
    const imgPreviewRef = ref<ImagePreviewInstance>()
    // 预览图片
    const onShowImage = (index: number) => {
      data.downIndex = data.startPosition = index
      data.imgShow = true
      // showImagePreview({
      //   images: images.value,
      //   closeable: true,
      //   startPosition: data.startPosition,
      //   onChange: (index: number) => (data.startPosition = index),
      // })
    }
    const imgTobase64 = (_img: any) => {
      const _canvas = document.createElement('canvas')
      _canvas.width = _img.width
      _canvas.height = _img.height
      const ctx = _canvas.getContext('2d')
      ctx?.drawImage(_img, 0, 0, _canvas.width, _canvas.height)
      // console.log(_img, _canvas)
      return _canvas.toDataURL('image/png')
    }
    const saveImg = async () => {
      const src = images.value[data.downIndex]
      if (data.downLoading || !src) return
      const t = showLoadingToast({
        message: '保存中',
        duration: 0
      })
      const _img = document.createElement('img')
      _img.crossOrigin = 'anonymous'
      _img.onload = async () => {
        // console.log("🚀 ~ base64:", base64)
        const base64 = imgTobase64(_img)
        try {
          const res = await promisefiyPostMessage({
            api: 'savePicture',
            content: {
              base64: base64
            }
          })
          if (res?.content?.status === 'success') {
            showSuccessToast('保存成功')
          } else {
            showFailToast('保存失败')
          }
        } catch (error) {}
        t.close()
        data.downLoading = false
      }
      _img.src = src + `?v=${Date.now()}`
    }

    onMounted(() => {
      getList()
      document.title = (route.query.name as any) || ''
    })

    return () => (
      <div>
        <OSticky
          onGetHeight={(height: number) => {
            document.documentElement.style.setProperty('--header-height', height + 'px')
          }}
        >
          <OHeader />
        </OSticky>
        <OFullRefresh
          modelValue={data.refreshing}
          onRefresh={() => {
            data.refreshing = true
            getList()
          }}
        >
          <div class={styles.phoneListDetailWrap}>
            <List
              // loading={data.loading}
              loadingText=" "
              finished={data.finished}
              finishedText=" "
              onLoad={getList}
              immediateCheck={false}
            >
              <div class={styles.phoneListDetail}>
                <TransitionGroup name="van-fade">
                  {data.list.map((item: any, index: number) => (
                    <div
                      key={`index-${index}`}
                      class={styles.gridItem}
                      onClick={() => onShowImage(index)}
                    >
                      <OImage class={styles.gridImg} src={item.fileUrl} />
                    </div>
                  ))}
                </TransitionGroup>
                {!data.loading && !data.list.length && (
                  <OEmpty key="OEmpty1" btnStatus={false} tips="暂无照片" />
                )}
              </div>
            </List>
          </div>
        </OFullRefresh>
        <ImagePreview
          ref={imgPreviewRef}
          v-model:show={data.imgShow}
          startPosition={data.startPosition}
          images={images.value}
          onChange={(index: number) => (data.downIndex = index)}
        >
          {{
            cover: () => (
              <div class={styles.downBtn} onClick={() => saveImg()}>
                <img src={iconDown} />
              </div>
            )
          }}
        </ImagePreview>
      </div>
    )
  }
})
