<template>
  <div class="accompanimentModal">
    <van-sticky :offset-top="isHead ? '.46rem' : 0">
      <van-dropdown-menu class="cateDropDown" active-color="#01C1B5">
        <van-dropdown-item
          v-if="levelOptions && levelOptions.length > 0"
          v-model="levelId"
          :options="levelOptions"
          @change="levelChange"
        />
        <van-dropdown-item
          v-model="subjectId"
          :options="subjectOptions"
          @change="subjectChange"
        />
      </van-dropdown-menu>
      <van-search
        v-model="search"
        show-action
        placeholder="请输入搜索关键词"
        shape="round"
      >
        <template #label>
          <van-dropdown-menu
            v-if="typeOptions && typeOptions.length > 0"
            class="headDropDown"
            active-color="#01C1B5"
          >
            <van-dropdown-item
              v-model="typeId"
              :options="typeOptions"
              @change="typeChange"
            />
          </van-dropdown-menu>
        </template>
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </van-sticky>

    <van-list
      v-model="loading"
      v-if="show"
      key="data"
      :finished="finished"
      finished-text="没有更多数据了"
      :immediate-check="false"
      @load="FetchList"
    >
      <van-cell-group>
        <van-cell
          v-for="(item, index) in list"
          :key="index"
          class="input-cell"
          clickable
          @click="onSelect(item)"
          :center="true"
        >
          <template slot="icon">
            <van-icon class="iconMusic" :name="MusicIcon" />
            <div class="icon" v-if="item.rankIds">
              <img src="./icons/vip_icon.png" />
            </div>
          </template>
          <template slot="title">
            <!-- {{ item.examSongName }} -->
            <van-notice-bar
              background="none"
              :style="{
                paddingLeft:
                  (item.rankIds ? '.04rem' : '.15rem') + '!important',
              }"
              color="#444"
              :scrollable="false"
              :text="item.name"
            />
          </template>
        </van-cell>
      </van-cell-group>
    </van-list>
    <!-- <m-empty class="empty" v-else key="data" /> -->
    <van-empty v-else description="暂无数据" key="data" />
  </div>
</template>

<script>
import { find } from "lodash";
import {
  // sysMusicScoreCategoriesTree,
  queryPageLimit,
  querySubjectIds,
} from "./api";
import MusicIcon from "./icons/music.png";
export default {
  props: {
    isHead: {
      type: Boolean,
      default() {
        return false;
      },
    },
    id: {
      type: [Number, String],
    },
    searchSubjectId: {
      type: [Number, String],
      default: 0,
    },
  },
  data() {
    return {
      MusicIcon,
      levelId: 0,
      subjectId: 0,
      levelOptions: [
        // { text: '全部等级', value: 0 },
      ],
      subjectOptions: [{ text: "全部声部", value: 0 }],
      typeId: 0,
      typeOptions: [],
      search: null,
      loading: false,
      finished: false,
      show: true,
      params: {
        page: 1,
        rows: 20,
      },
      list: [],
    };
  },
  computed: {
    parentId() {
      return this.id || 1;
    },
  },
  async mounted() {
    this.subjectId = Number(this.searchSubjectId)
    await this.FetchLevel();
    await this.FetchList();
  },
  methods: {
    async FetchLevel() {
      try {
        const musicScoreList = sessionStorage.getItem("musicScoreList");
        const musicList = musicScoreList ? JSON.parse(musicScoreList) : [];
        let childClass = [];
        for (let music of musicList) {
          if (music.id == this.parentId) {
            childClass = music.sysMusicScoreCategoriesList || [];
          }
        }
        this.levelOptions = [
          ...childClass.map((item) => ({
            value: item.id,
            text: item.name,
            childs: item.sysMusicScoreCategoriesList,
          })),
        ];
        if (this.levelOptions.length && !this.levelId) {
          this.levelId = this.levelOptions[0].value;
          const active = find(this.levelOptions, { value: this.levelId });
          if (active) {
            if (active.childs) {
              this.typeOptions = [
                { value: 0, text: "全部练习" },
                ...active.childs.map((item) => ({
                  value: item.id,
                  text: item.name,
                })),
              ];
            } else {
              this.typeOptions = null;
            }
          }
        }
        // console.log(this.levelOptions, 'levelOptions')
        // console.log(this.typeOptions, 'typeOptions')
      } catch (error) {}
    },
    async FetchCats() {
      try {
        const res = await querySubjectIds();
        this.subjectOptions = [
          ...this.subjectOptions,
          ...res.data
            .filter((item) => !!item)
            .map((item) => ({ value: item.id, text: item.name })),
        ];
        let subjectStatus = false // 判断是否存在声部
        this.subjectOptions.forEach(subject => {
          if(this.subjectId == subject.value) {
            subjectStatus = true
          }
        });
        // 如果声部列表中没有数据,则默认选中0
        this.subjectId = subjectStatus ? this.subjectId : 0
      } catch (error) {
        //
      }
    },
    async FetchList() {
      if (this.subjectOptions.length === 1) {
        await this.FetchCats();
      }
      try {
        let params = this.params;
        let categoriesId = ((this.levelId || this.typeId) === 0 ? undefined : this.typeId || this.levelId) || this.parentId
        const res = await queryPageLimit({
          ...params,
          clientType: "SMART_PRACTICE",
          subjectId: this.subjectId === 0 ? undefined : this.subjectId,
          categoriesId,
          search: this.search,
        });
        this.loading = false;
        const { data } = res;
        this.list = [...this.list, ...data.rows];
        if (params.page >= Math.ceil(data.totalPage)) {
          this.finished = true;
          // Toast('列表加载完成')
        }
        this.params.page = data.nextPage;
        if (this.list.length <= 0) {
          this.show = false;
        }
      } catch(e) {
        //
        console.log(e)
      }
    },
    levelChange(val) {
      this.levelId = val;
      this.typeId = 0;
      const active = find(this.levelOptions, { value: val });
      if (active) {
        if (active.childs) {
          this.typeOptions = [
            { value: 0, text: "全部练习" },
            ...active.childs.map((item) => ({
              value: item.id,
              text: item.name,
            })),
          ];
        } else {
          this.typeOptions = null;
        }
      }
      this.onSearch();
    },
    subjectChange(val) {
      this.subjectId = val;
      this.onSearch();
    },
    typeChange(val) {
      this.typeId = val;
      this.onSearch();
    },
    onSearch() {
      this.params.page = 1;
      this.list = [];
      this.show = true;
      this.finished = false;
      this.FetchList();
    },
    onSelect(item) {
      this.$emit("onSelectMusic", item);
    },
  },
};
</script>

<style lang="less" scoped>
.accompanimentModal {
  background-color: #f5f5f5;
  min-height: 100vh;

  /deep/.van-search {
    .van-cell {
      font-size: 0.14rem;
      padding: 0.05rem 0.08rem;
      line-height: 0.24rem;
    }
    .van-dropdown-menu__bar {
      height: 0.36rem;
      background: transparent;
      box-shadow: none;
    }
  }

  .headDropDown {
    height: 0.36rem;
    background: transparent;
    /deep/.van-dropdown-menu__title {
      font-size: 0.14rem;
    }
  }
  /deep/.van-field__control {
    font-size: 0.14rem;
  }
  /deep/.van-dropdown-item .van-cell {
    padding: 0.12rem 0.16rem;
  }

  .iconMusic {
    /deep/.van-icon__image {
      width: 0.38rem;
      height: 0.38rem;
      margin: auto;
      vertical-align: middle;
      // padding-right: .1rem;
    }
  }

  .icon {
    display: flex;
    align-items: center;
    margin-left: 0.15rem;
    img {
      width: 0.4rem;
      // margin-top: -.02rem;
    }
  }
}
</style>
