import { defineComponent, ref } from 'vue'
import { Button, Icon, Image, Popup, Tag, Toast } from 'vant'
import classNames from 'classnames'
import MusicIcon from './icons/music-icon.png'
import InitUserIcon from './icons/init-user-icon.png'
import FavoriteIcon from '../album/favorite.svg'
import FavoritedIcon from '../album/favorited.svg'
import iconShare from '../album/icon_share.svg'
import styles from './item.module.less'
import request from '@/helpers/request'
import { state } from '@/state'
import ColShare from '@/components/col-share'

const chargeTypes = {
  CHARGE: '点播',
  FREE: '免费',
  VIP: 'VIP'
}

export default defineComponent({
  name: 'MusicItem',
  props: {
    data: {
      type: Object,
      default: {}
    },
    onClick: {
      type: Function
    }
  },
  emits: ['favorite'],
  setup({ onClick, data }, { emit }) {
    // const data = props.data
    // console.log(props, emit)
    const favorite = ref(data.favorite)
    const favoriteLoading = ref(false)
    const titleImg = data.titleImg + '?t=' + +new Date()

    const toggleFavorite = async (evt: MouseEvent) => {
      evt.stopPropagation()
      favoriteLoading.value = true
      try {
        await request.post('/music/sheet/favorite/' + data.id, {
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
        })
        favorite.value = !favorite.value
      } catch (error) {}
      favoriteLoading.value = false
      emit('favorite')
    }

    const shareStatus = ref(false)
    const shareUrl = ref('')
    const shareDiscount = ref(0)
    // console.log(data)
    const onShare = async (evt: MouseEvent) => {
      evt.stopPropagation()

      try {
        const res = await request.post('/api-teacher/open/musicShareProfit', {
          data: {
            bizId: data.id,
            userId: state.user.data?.userId
          }
        })
        let url =
          location.origin +
          `/accompany/colexiu-share.html?id=${data.id}&recomUserId=${state.user.data?.userId}`
        // 判断是否有活动
        if (res.data.discount === 1) {
          url += `&activityId=${res.data.activityId}`
        }
        shareDiscount.value = res.data.discount || 0
        shareUrl.value = url
        shareStatus.value = true
        return
      } catch {}

      // if (!shareStatus.value) {
      //   Toast('暂无分享地址')
      //   return
      // }
      // https://dev.colexiu.com/accompany/colexiu-share.html?id=2500&recomUserId=1
    }
    return () => (
      <div>
        <div
          class={styles.item}
          onClick={() => {
            onClick?.(data)
          }}
        >
          <header class={[styles.header, 'van-hairline--bottom']}>
            <div class={styles.mate}>
              <Image
                src={data.titleImg || MusicIcon}
                round
                class={styles.icon}
              />
              <div class={styles.info}>
                <h4 class="van-multi-ellipsis--l2">{data.musicSheetName}</h4>
                <p>{data.composer}</p>
              </div>
            </div>
            <div class={styles.buttons}>
              <Button
                class={classNames(
                  styles.btn,
                  styles[data.chargeType.toLocaleLowerCase()]
                )}
              >
                {chargeTypes[data.chargeType]}
                <Icon name="arrow" />
              </Button>
            </div>
          </header>
          <footer class={styles.footer}>
            <div class={styles.user}>
              <Image
                round
                src={data.addUserAvatar || InitUserIcon}
                class={styles.userIcon}
              />
              <p>{data.addName}</p>
              <div class={styles.tags}>
                {(data.subjectNames || '').split(',').map(item => (
                  <Tag>{item}</Tag>
                ))}
              </div>
            </div>
            <div class={styles.icons}>
              {state.platformType === 'STUDENT' ? (
                <Button
                  style={{ border: 'none' }}
                  onClick={toggleFavorite}
                  loading={favoriteLoading.value}
                >
                  <Icon
                    class={styles.favorite}
                    name={favorite.value ? FavoritedIcon : FavoriteIcon}
                  />
                </Button>
              ) : (
                <Button
                  style={{ border: 'none' }}
                  class={styles.shareBtn}
                  onClick={onShare}
                >
                  <Icon class={styles.favorite} name={iconShare} />
                </Button>
              )}
            </div>
          </footer>
        </div>
        <Popup
          v-model:show={shareStatus.value}
          style={{ background: 'transparent' }}
          teleport="body"
        >
          <ColShare
            teacherId={data.userId}
            shareUrl={shareUrl.value}
            shareType="music"
          >
            <div class={styles.shareMate}>
              {shareDiscount.value === 1 && (
                <div class={styles.tagDiscount}>专属优惠</div>
              )}

              <img
                class={styles.icon}
                crossorigin="anonymous"
                src={data.titleImg + `?t=${+new Date()}` || MusicIcon}
              />
              <div class={styles.info}>
                <h4 class="van-multi-ellipsis--l2">{data.musicSheetName}</h4>
                <p>作曲人：{data.composer}</p>
              </div>
            </div>
          </ColShare>
        </Popup>
      </div>
    )
  }
})
