import { CellGroup, Cell, Icon, Image, Popup, Tag, Toast } from 'vant'
import { defineComponent, PropType, ref } from 'vue'
import styles from './index.module.less'
import IconPlay from '@/common/images/icon-play.png'
import IconMore from '@/common/images/icon_more.png'
import { useRouter } from 'vue-router'
import { state } from '@/state'
import request from '@/helpers/request'
import ColShare from '@/components/col-share'
import MusicIcon from '../../list/icons/music-icon.png'
export const getAssetsHomeFile = (fileName: string) => {
  const path = `../images/${fileName}`
  const modules = import.meta.globEager('../images/*')
  return modules[path].default
}
export default defineComponent({
  name: 'TheSong',
  props: {
    list: {
      type: Array as PropType<any[]>,
      default: () => []
    }
  },
  emits: ['detail'],
  setup(props, { emit }) {
    const isMore = ref<boolean>(false)
    const moreData = ref<any>({})
    const router = useRouter()
    const colors: any = {
      FREE: {
        color: '#01B84F',
        text: '免费'
      },
      VIP: {
        color: '#CD863E',
        text: '会员'
      },
      CHARGE: {
        color: '#3591CE',
        text: '点播'
      }
    }

    const toggleFavorite = async () => {
      try {
        await request.post('/music/sheet/favorite/' + moreData.value.id, {
          prefix:
            state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
        })
        moreData.value.favorite = moreData.value.favorite ? 0 : 1
        setTimeout(() => {
          Toast(moreData.value.favorite ? '收藏成功' : '取消收藏成功')
          isMore.value = false
        }, 100)
      } catch (error) {}
    }

    const shareStatus = ref(false)
    const shareUrl = ref('')
    const shareDiscount = ref(0)
    // console.log(data)
    const onShare = async () => {
      try {
        const res = await request.post('/api-teacher/open/musicShareProfit', {
          data: {
            bizId: moreData.value.id,
            userId: state.user.data?.userId
          }
        })
        let url =
          location.origin +
          `/accompany/colexiu-share.html?id=${moreData.value.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
        isMore.value = false
        shareStatus.value = true
        return
      } catch {}
    }

    return () => (
      <div class={styles.theSong}>
        {props.list.map((n: any) => (
          <div class={styles.item} onClick={() => emit('detail', n)}>
            <div class={styles.content}>
              <div class={styles.top}>
                <Tag
                  style={{ color: colors[n.chargeType].color }}
                  class={styles.tag}
                  type="success"
                  plain
                >
                  {colors[n.chargeType].text}
                </Tag>
                <span class={[styles.title, 'van-ellipsis']}>
                  {n.musicSheetName}
                </span>
                <span class={[styles.singer, 'van-ellipsis']}>
                  -{n.composer}
                </span>
              </div>
              <div class={styles.user}>
                {n.favorite === 1 && (
                  <Image
                    src={getAssetsHomeFile('collection_active.png')}
                    class={styles.collection}
                  />
                )}
                {n.addName ? (
                  <span class={styles.name}>上传者：{n.addName}</span>
                ) : (
                  <span class={styles.name}>作曲：{n.composer}</span>
                )}
                <div class={styles.tags}>
                  {n?.subjectNames.split(',').map((name: any) => (
                    <span>{name}</span>
                  ))}
                </div>
              </div>
            </div>
            <div class={styles.play}>
              <Icon name={IconPlay} size={28} />

              <span class={styles.moreSection}>
                <Icon
                  name={IconMore}
                  size={18}
                  onClick={(e: MouseEvent) => {
                    e.stopPropagation()
                    isMore.value = true
                    moreData.value = n
                  }}
                />
              </span>
            </div>
          </div>
        ))}

        <Popup v-model:show={isMore.value} position="bottom" round>
          <CellGroup border={false}>
            <Cell
              center
              class={styles.musicInfo}
              v-slots={{
                icon: () => (
                  <Image class={styles.pImg} src={moreData?.value.titleImg} />
                ),
                title: () => (
                  <div class={styles.info}>
                    <h4 class="van-ellipsis">
                      {moreData?.value.musicSheetName}
                    </h4>
                    <p
                      style={{
                        display: 'flex'
                      }}
                    >
                      <Tag
                        style={{
                          color: colors[moreData?.value.chargeType].color,
                          marginRight: '6px'
                        }}
                        class={styles.tag}
                        type="success"
                        plain
                      >
                        {colors[moreData?.value.chargeType].text}
                      </Tag>
                      <span style={{ paddingTop: '2px' }}>
                        {moreData?.value.composer}
                      </span>
                    </p>
                  </div>
                )
              }}
            />
            {state.platformType === 'STUDENT' && (
              <Cell
                border={false}
                size="large"
                title={moreData.value.favorite ? '取消收藏' : '收藏曲目'}
                center
                onClick={() => toggleFavorite()}
                v-slots={{
                  icon: () => (
                    <div class={styles.shareIcon}>
                      <Image
                        src={
                          moreData.value.favorite
                            ? getAssetsHomeFile('collection_active.png')
                            : getAssetsHomeFile('collection.png')
                        }
                      />
                    </div>
                  )
                }}
              />
            )}
            {state.platformType === 'TEACHER' && (
              <Cell
                border={false}
                size="large"
                title={'分享曲目'}
                center
                onClick={() => onShare()}
                v-slots={{
                  icon: () => (
                    <div class={styles.shareIcon}>
                      <Image
                        class={styles.share}
                        src={getAssetsHomeFile('icon_share.png')}
                      />
                    </div>
                  )
                }}
              />
            )}

            <Cell
              border={false}
              size="large"
              center
              title={`作曲：${moreData.value?.composer}`}
              v-slots={{
                icon: () => (
                  <div class={styles.shareIcon}>
                    <Image src={getAssetsHomeFile('icon_author.png')} />
                  </div>
                )
              }}
            />
            <Cell
              border={false}
              size="large"
              center
              title={`上传：${moreData.value?.addName || '--'}`}
              v-slots={{
                icon: () => (
                  <div class={styles.shareIcon}>
                    <Image src={getAssetsHomeFile('icon_uploader.png')} />
                  </div>
                )
              }}
            />
            <Cell
              border={false}
              size="large"
              title={'小酷Ai练习'}
              isLink
              center
              style={{ marginBottom: '100px' }}
              onClick={() => {
                isMore.value = false
                emit('detail', moreData.value)
              }}
              v-slots={{
                icon: () => (
                  <div class={styles.shareIcon}>
                    <Image src={getAssetsHomeFile('icon_ai.png')} />
                  </div>
                )
              }}
            />
          </CellGroup>
        </Popup>

        <Popup
          v-model:show={shareStatus.value}
          style={{ background: 'transparent' }}
          teleport="body"
        >
          <ColShare
            teacherId={moreData.value?.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={
                  moreData.value?.titleImg +
                    `@base@tag=imgScale&h=80&w=80&m=1?t=${+new Date()}` ||
                  MusicIcon
                }
              />
              <div class={styles.info}>
                <h4 class="van-multi-ellipsis--l2">
                  {moreData.value?.musicSheetName}
                </h4>
                <p>作曲人：{moreData.value?.composer}</p>
              </div>
            </div>
          </ColShare>
        </Popup>
      </div>
    )
  }
})
