import { computed, defineComponent, onMounted, reactive, watch, ref } from "vue";
import styles from "./index.module.less";
import { api_musicSheetPage, api_musicIsBuy } from "../../api";
import state, { togglePlay } from "/src/state";
import { List, Image, Field, DropdownMenu, DropdownItem } from "vant";
import { postMessage } from "/src/utils/native-message";
import qs from "query-string";
import searImg from "./imgs/searImg.png"
import huoimg from "./imgs/huo.png"
import emptyImg from "./imgs/empty.png"
import { getQuery } from "/src/utils/queryString";
import { vipData } from "../vip"
import { permissionPopup } from "../vip/permission";
import { storeData } from "/src/store";
import vipIcon from "./imgs/icon-music-vip.png"
import vip1Icon from "./imgs/icon-music-vip1.png"
import sbuyIcon from "./imgs/icon-music-sbuy.png"

export default defineComponent({
  name: "TheMusicList-list",
  props: {
    // 最近练习
    recentFlag: {
      type: Boolean,
      default: false,
    },
    // 我的收藏
    favoriteFlag: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const query: any = getQuery();
    const forms = reactive({
      name: "",
      page: 1,
      rows: 20,
      musicalInstrumentId: state.specialPercussionFlag ? state.musicalInstrumentIds.split(",")[0] : (state.isConcert ? "" : state.instrumentId),
      musicSheetCategoriesId: state.bizMusicCategoryId,
      recentFlag: props.recentFlag ? true : null, // 最近练习
      favoriteFlag: props.favoriteFlag ? true : null, // 我的收藏
      excludeMusicId: props.recentFlag || props.favoriteFlag ? null : state.examSongId,
      albumId: query.albumId ? query.albumId : null,
      providerType: state.tenantAlbumId ? "TENANT" : "PLATFORM"
    });
    const data = reactive({
      isFocus: false,
      list: [] as any[],
      finished: false,
      loading: false,
      hasNext: true,
    });
    const loading = ref(false)

    const getList = async () => {
      if (!data.hasNext) return;
      data.loading = true;
      try {
        const res = await api_musicSheetPage({
          ...forms
        });
        if (res?.code === 200 && Array.isArray(res.data?.rows)) {
          res.data.rows.forEach((item: any) => item.useStatus = 'LOCK')
          data.list = [...data.list, ...res.data.rows];
        }
        data.finished = res.data?.rows?.length < forms.rows;
        data.hasNext = res.data?.total > data.list.length;
      } catch (error) {
        console.log(error);
      }

      data.loading = false;
    };
    function handleQuery(){
      forms.page = 1
      forms.rows = 20
      data.list = []
      data.finished =false
      data.loading = false
      data.hasNext = true
      getList()
    }
    watch(
      () => props.recentFlag,
      () => {
        data.hasNext = true;
      }
    );
    watch(
      () => props.favoriteFlag,
      () => {
        data.hasNext = true;
      }
    );
    onMounted(() => {
      getList();
    });

    const openAccomapina = async (item: any) => {
      if (item.id === state.examSongId) return;
      // 学生端或者老师端需要校验点播和会员曲目；通过专辑进入的，不需要校验点播和会员曲目，默认都可以使用
      if (vipVerify.value && !state.tenantAlbumId) {
        // 是否需要校验vip
        let needCheckVip = true;
        if (item.paymentType.includes("VIP") && ["VIP","SVIP","PERMANENT_SVIP"].includes(state.vipType)) {
          needCheckVip = false;
        } else {
          // 如果是点播的曲子，需要弹窗提醒
          if (item.paymentType.includes("CHARGE")) {
            if (loading.value === true) return
            loading.value = true
            // 查询是否购买了
            const { data } = await api_musicIsBuy(item.id)
            loading.value = false
            if (data.buyed === false) {
              permissionPopup.active = item.paymentType === "CHARGE" ? "demand" : "memberAndDemand"
              permissionPopup.musicId = item.id
              permissionPopup.musicPrice = item.musicPrice
              permissionPopup.show = true
              return
            }
            // 已经购买
            if (data.buyed === true) {
              needCheckVip = false;
            }
          }
          // 如果是vip的曲子，当前用户不是会员时，需要弹窗提醒
          if (state.vipType === "NOT_VIP" && item.paymentType !== "FREE" && needCheckVip) {
            permissionPopup.active = item.paymentType.includes('CHARGE') ? "memberAndDemand" : "member"
            permissionPopup.musicId = item.id
            permissionPopup.musicPrice = item.musicPrice
            permissionPopup.show = true
            return
          }
        }
      }
      
      // 暂停播放
      togglePlay("paused");
      postMessage({
        api: "cloudLoading",
        content: {
          show: true,
          type: "fullscreen",
        },
      });
      const queryObj = {
        ...query
      }
      queryObj.id = item.id
      queryObj["part-index"] = ""
      location.href =
        location.origin +
        location.pathname +
          "?" +
          qs.stringify(queryObj);
    };
    function formatNumber(num:number) {
      return num >= 10000 
          ? (num / 10000).toFixed(1).replace(/\.0$/, '') + "万" 
          : num.toString();
    }
    const vipVerify = computed(() => {
      return state.systemType === "student" || state.systemType === "teacher"
    })
    return () => (
      <div class={styles.wrap}>
        <div class={[styles.searchBox,data.isFocus && styles.isFocus]}>
          <img src={searImg} />
          <Field placeholder="请输入曲目名称" v-model={forms.name} autocomplete="off" onFocus={()=>{ data.isFocus = true }} onBlur={()=>{ data.isFocus = false }} />
          <div class={styles.searchBtn} onClick={handleQuery}>搜索</div>
        </div>
        <List
          loading={data.loading}
          finished={data.finished}
          immediateCheck={false}
          onLoad={() => {
            forms.page++;
            getList();
          }}
        >
          {data.list.map((item: any) => {
            return (
              <div class={[styles.item, state.examSongId == item.id && styles.itemActive]} onClick={() => openAccomapina(item)}>
                <div class={styles.titleImg}>
                  {/* {
                    item.useStatus==='LOCK'&&vipVerify.value && <div class={styles.lock}></div>
                  } */}
                  {
                    (item.paymentType.includes('VIP') || item.paymentType.includes('CHARGE')) && 
                    <img 
                      class={styles.vipIcon}
                      src={item.paymentType === 'VIP' ? vipIcon : item.paymentType === 'CHARGE' ? sbuyIcon : item.paymentType === 'VIP,CHARGE' || item.paymentType === 'CHARGE,VIP' ? vip1Icon : ''} 
                    />                    
                  }
                  <Image src={item.titleImg} class={styles.img} />
                </div>
                <div class={styles.content}>
                  <div class={styles.name}>{item.musicSheetName}</div>
                  {          
                    ((["FREE","LOCK"].includes(item.useStatus)&&vipVerify.value) || item.composer) &&
                    <div class={styles.detail}>
                      {/* {item.usedNum && <div class={styles.usedNum}><img src={huoimg}/><div>{formatNumber(item.usedNum)}</div></div>} */}
                      {/* {
                        item.useStatus==='FREE'&&vipVerify.value && <div class={[styles.freeIcon]}>试用</div>
                      }
                      {
                        item.useStatus==='LOCK'&&vipVerify.value && <div class={[styles.lockIcon]}>未解锁</div>
                      } */}
                      {
                        item.composer && <div class={styles.author}>{item.composer}</div>
                      }
                    </div>
                  }
                </div>
              </div>
            );
          })}
          {!data.loading && data.list.length === 0 
            &&  <div class={styles.empty}>
                  <img src={emptyImg}/>
                  <span>暂无内容</span>
                </div>}
        </List>
      </div>
    );
  },
});
