import { defineComponent, ref } from 'vue'
import { Button, Icon, Image, Tag } 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 styles from './item.module.less'
import request from '@/helpers/request'

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 toggleFavorite = async (evt: MouseEvent) => {
      evt.stopPropagation()
      favoriteLoading.value = true
      try {
        await request.post('/api-student/music/sheet/favorite/' + data.id)
        favorite.value = !favorite.value
      } catch (error) {}
      favoriteLoading.value = false
      emit('favorite')
    }
    return () => (
      <div
        class={styles.item}
        onClick={() => {
          onClick?.(data)
        }}
      >
        <header class={styles.header}>
          <div class={styles.mate}>
            <Image src={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}>
            <Button
              style={{ border: 'none' }}
              onClick={toggleFavorite}
              loading={favoriteLoading.value}
            >
              <Icon
                class={styles.favorite}
                name={favorite.value ? FavoritedIcon : FavoriteIcon}
              />
            </Button>
          </div>
        </footer>
      </div>
    )
  }
})
