import { defineComponent, onMounted, reactive } from "vue";
import styles from "./index.module.less";
import { api_musicSheetPage } from "../../api";
import state, { togglePlay } from "/src/state";
import { List } from "vant";
import { postMessage } from "/src/utils/native-message";
import qs from "query-string";

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

			data.loading = false;
		};
		onMounted(() => {
			getList();
		});

		const openAccomapina = (item: any) => {
			if (item.id === state.examSongId) return;
			// 暂停播放
			togglePlay("paused");
			postMessage({
				api: "cloudLoading",
				content: {
					show: true,
					type: "fullscreen",
				},
			});
			location.href =
				location.origin +
				location.pathname +
				"?" +
				qs.stringify({
					id: item.id,
					_t: Date.now(),
				});
		};
		return () => (
			<div class={styles.wrap}>
				<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)}
							>
								{item.musicSheetName}
							</div>
						);
					})}
					{!data.loading && data.list.length === 0 && <div class={styles.noData}>暂无数据</div>}
				</List>
			</div>
		);
	},
});
