import { Button, Cell, Swipe, SwipeItem, Toast } from 'vant'
import { defineComponent, PropType } from 'vue'
import styles from './index.module.less'
import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
import html2canvas from 'html2canvas'
import ShareItem from './share-item'
import request from '@/helpers/request'

export default defineComponent({
  name: 'col-share',
  props: {
    type: {
      type: String as PropType<'default' | 'tenant'>,
      default: 'default'
    },
    teacherId: {
      type: Number
    },
    shareUrl: {
      type: String,
      default: ''
    },
    shareType: {
      // 分享类型
      type: String as PropType<
        '' | 'video' | 'music' | 'live' | 'mall' | 'vip' | 'album'
      >,
      default: ''
    },
    shareLength: {
      type: Number,
      default: 3
    }
  },
  data() {
    const tempArray: any = []
    for (let i = 0; i < this.shareLength; i++) {
      tempArray.push(i)
    }
    console.log(tempArray)
    return {
      swiperIndex: 0,
      image: null as any,
      codeUrl: '',
      copyCodeUrl: '',
      shareLoading: false,
      shareArray: tempArray || [],
      saveLoading: false,
      showType: ['', 'yellow', 'pink'] as any
    }
  },
  async mounted() {
    try {
      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() {
      // 判断是否在保存中...
      if (this.saveLoading) {
        return
      }
      this.saveLoading = true
      // 判断是否已经生成图片
      if (this.image) {
        this.saveImg()
      } else {
        const container: any = document.getElementById(
          `share-preview-container${this.swiperIndex}`
        )
        html2canvas(container, {
          allowTaint: true,
          useCORS: true,
          backgroundColor: null
        })
          .then(async canvas => {
            const url = canvas.toDataURL('image/png')
            this.image = url
            this.saveImg()
          })
          .catch(() => {
            Toast.clear()
            this.saveLoading = false
          })
      }
    },
    async saveImg() {
      Toast.loading({
        message: '图片生成中...',
        forbidClick: true
      })
      setTimeout(() => {
        this.saveLoading = false
      }, 100)
      const res = await promisefiyPostMessage({
        api: 'savePicture',
        content: {
          base64: this.image
        }
      })
      if (res?.content?.status === 'success') {
        Toast.success('已保存到相册')
      } else {
        Toast.fail('保存失败')
      }
    },
    async shareShow() {
      // 判断是否在分享中...
      if (this.shareLoading) {
        return
      }
      this.shareLoading = true
      if (this.image) {
        this.openShare()
      } else {
        const container: any = document.getElementById(
          `share-preview-container${this.swiperIndex}`
        )
        html2canvas(container, {
          allowTaint: true,
          useCORS: true,
          backgroundColor: null
        })
          .then(async canvas => {
            const url = canvas.toDataURL('image/png')
            this.image = url

            this.openShare()
          })
          .catch(() => {
            Toast.clear()
            this.shareLoading = false
          })
      }
    },
    openShare() {
      const image = this.image
      setTimeout(() => {
        this.shareLoading = false
      }, 100)
      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">
              <Swipe
                showIndicators={true}
                // loop={false}
                lazyRender={true}
                onChange={(index: number) => {
                  this.swiperIndex = index
                  // 当前显示分享的图片切换时，则需要重置图片
                  this.image = null
                }}
                v-slots={{
                  indicator: (active: any) =>
                    this.shareArray.length > 1 && (
                      <div class={styles.swipe__indicators}>
                        <div class={styles.indicators}>
                          {Array.from({ length: active.total }, (_, i) => (
                            <div
                              class={[
                                styles.swipe__indicator,
                                i == active.active &&
                                  styles['swipe__indicator--active']
                              ]}
                            ></div>
                          ))}
                        </div>
                        <div class={styles.total}>
                          分享模板 {active.active + 1}/{active.total}
                        </div>
                      </div>
                    )
                }}
              >
                {this.shareArray.map((item: any, index: number) => (
                  <SwipeItem>
                    <ShareItem
                      id={`share-preview-container${index}`}
                      teacherId={this.teacherId}
                      shareUrl={this.codeUrl}
                      shareType={this.shareType}
                      showType={this.showType[index]}
                    >
                      {this.$slots.default && this.$slots.default()}
                    </ShareItem>
                  </SwipeItem>
                ))}
                {/* <SwipeItem>
                  <ShareItem
                    id="share-preview-container0"
                    teacherId={this.teacherId}
                    shareUrl={this.codeUrl}
                    shareType={this.shareType}
                  >
                    {this.$slots.default && this.$slots.default()}
                  </ShareItem>
                </SwipeItem> */}
                {/* <SwipeItem>
                  <ShareItem
                    id="share-preview-container1"
                    teacherId={this.teacherId}
                    shareUrl={this.codeUrl}
                    showType="yellow"
                    shareType={this.shareType}
                  >
                    {this.$slots.default && this.$slots.default()}
                  </ShareItem>
                </SwipeItem>
                <SwipeItem>
                  <ShareItem
                    id="share-preview-container2"
                    teacherId={this.teacherId}
                    shareUrl={this.codeUrl}
                    showType="pink"
                    shareType={this.shareType}
                  >
                    {this.$slots.default && this.$slots.default()}
                  </ShareItem>
                </SwipeItem> */}
              </Swipe>
            </div>

            <div
              class={[
                'btnGroup',
                styles.shareGroupBtn,
                this.type === 'tenant' ? styles.shareGroupTenantBtn : ''
              ]}
            >
              <Button
                type="primary"
                plain
                round
                loading={this.saveLoading}
                loadingText="保存中"
                onClick={this.onSaveImg}
              >
                保存图片
              </Button>
              <Button
                type="primary"
                round
                loading={this.shareLoading}
                loadingText="分享中"
                onClick={() => {
                  this.shareShow()
                }}
              >
                立即分享
              </Button>
            </div>
          </>
        )}
      </>
    )
  }
})
