import { defineComponent, onMounted, reactive, watch } from "vue";
import styles from "./index.module.less";
import { api_musicSheetPage } 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, isVip } from "../vip"

export default defineComponent({
  name: "TheMusicList-list",
  props: {
    recentFlag: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const query: any = getQuery();
    const forms = reactive({
      name: "",
      page: 1,
      rows: 20,
      musicalInstrumentId: state.isConcert ? "" : state.instrumentId,
      musicSheetCategoriesId: state.bizMusicCategoryId,
      recentFlag: props.recentFlag ? true : null,
      excludeMusicId: props.recentFlag ? null : state.examSongId,
    });
    const data = reactive({
      isFocus: false,
      list: [] as any[],
      finished: false,
      loading: false,
      hasNext: true,
    });
    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)) {
          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;
      }
    );
    onMounted(() => {
      getList();
    });

    const openAccomapina = (item: any) => {
      // 学生端 没有开会员查看会员曲目
      if(item.paymentType === "VIP" && state.systemType === "student" && !isVip.value){
        vipData.show = true
        return
      }
      // 学校查看会员曲目
      if(item.paymentType === "VIP" && state.systemType === "web" && state.isSchool){
        vipData.show = true
        return
      }
      if (item.id === state.examSongId) 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();
    }
    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}>
                  <i class={[styles.iconType, styles[item.paymentType]]}></i>
                  <Image src={item.titleImg} class={styles.img} />
                </div>
                <div class={styles.content}>
                  <p class={styles.name}>{item.musicSheetName}</p>
                  {
                    item.composer &&                   
                    <div class={styles.detail}>
                      {/* {item.usedNum && <div class={styles.usedNum}><img src={huoimg}/><div>{formatNumber(item.usedNum)}</div></div>} */}
                      <p class={styles.author}>{item.composer}</p>
                    </div>
                  }
                </div>
              </div>
            );
          })}
          {!data.loading && data.list.length === 0 
            &&  <div class={styles.empty}>
                  <img src={emptyImg}/>
                  <span>暂无内容</span>
                </div>}
        </List>
      </div>
    );
  },
});
