import { state } from '@/state'
import { Button, Cell, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import { postMessage } from '@/helpers/native-message'
import CodeDownload from '@/components/col-share/code-down-load'
import html2canvas from 'html2canvas'
import request from '@/helpers/request'
export const getAssetsHomeFile = (fileName: string) => {
  const path = `./images/${fileName}`
  const modules = import.meta.globEager('./images/*')
  return modules[path].default
}
import dayjs from 'dayjs'
import { promisefiyPostMessage } from '@/helpers/native-message'
export default defineComponent({
  name: 'share-model',
  props: {
    shareUrl: {
      type: String,
      default: ''
    },
    activeInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      image: null as any,
      copyCodeUrl: '',
      codeUrl: '',
      subjectUrl: ''
    }
  },
  async mounted() {
    try {
      // this.subjectUrl = this.activeInfo.subjectUrl + `?t=${dayjs().unix()}`
      this.subjectUrl = this.activeInfo.shareUrl + '?t=' + +new Date()
      console.log(this.shareUrl)
      const shortRes = await request.post('/api-teacher/sysConfig/shortURL', {
        requestType: 'form',
        data: {
          orginURL: this.shareUrl
        }
      })
      this.copyCodeUrl = shortRes.data
      this.codeUrl = this.shareUrl
    } catch {
      //
    }
  },
  methods: {
    async onSaveImg() {
      const container: any = document.getElementById('share-preview-container')
      html2canvas(container, { allowTaint: true, useCORS: true }).then(
        async canvas => {
          const url = canvas.toDataURL('image/png')
          this.image = url
          Toast.loading({
            message: '图片生成中...',
            forbidClick: true
          })
          const res = await promisefiyPostMessage({
            api: 'savePicture',
            content: {
              base64: this.image
            }
          })
          if (res?.content?.status === 'success') {
            Toast.success('已保存到相册')
          } else {
            Toast.fail('保存失败')
          }
        }
      )
    },
    async shareShow() {
      const container: any = document.getElementById('share-preview-container')
      html2canvas(container, { allowTaint: true, useCORS: true }).then(
        async canvas => {
          const url = canvas.toDataURL('image/png')
          this.image = url

          const image = this.image
          if (image) {
            postMessage(
              {
                api: 'shareAchievements',
                content: {
                  title: '',
                  desc: '',
                  image,
                  video: '',
                  type: 'image',
                  button: ['copy'],
                  url: this.copyCodeUrl
                }
              },
              (res: any) => {
                if (res && res.content) {
                  Toast(
                    res.content.message ||
                      (res.content.status ? '分享成功' : '分享失败')
                  )
                }
              }
            )
          }
        }
      )
    }
  },
  render() {
    return (
      <>
        {this.codeUrl && (
          <>
            <div
              class={styles.shareContainer}
              id="share-preview-container"
              style={{
                // backgroundImage: `url(${this.subjectUrl})`,
                // backgroundPosition: 'top center',
                backgroundColor: this.activeInfo.backgroundUrl
                // backgroundRepeat: 'no-repeat',
                // backgroundSize: 'contain'
              }}
            >
              <img
                class={[styles.cover]}
                src={this.subjectUrl}
                crossorigin="anonymous"
                style={{
                  objectFit: 'cover'
                }}
              />
              <div class={styles.reviewContainer}>
                <div
                  class={[
                    styles.section,
                    styles.activeTime,
                    styles.shareActiveTime
                  ]}
                >
                  <div class={styles.activeBg}>
                    <img src={getAssetsHomeFile('icon_time.png')} />
                    <p>
                      <span>活动时间：</span>
                      {dayjs(this.activeInfo.activityStart).format(
                        'YYYY-MM-DD'
                      )}
                      ~{dayjs(this.activeInfo.activityEnd).format('YYYY-MM-DD')}
                    </p>
                  </div>
                </div>

                <div class={[styles.section, styles.shareSection]}>
                  {this.activeInfo.describe}
                </div>
              </div>
              <div class={styles.shareCodeUrl}>
                <CodeDownload shareUrl={this.codeUrl} />
              </div>
            </div>
            <div class={['btnGroup', styles.shareGroupBtn]}>
              <Button type="primary" plain round onClick={this.onSaveImg}>
                保存图片
              </Button>
              <Button type="primary" round onClick={this.shareShow}>
                立即分享
              </Button>
            </div>
          </>
        )}
      </>
    )
  }
})
