import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch
} from 'vue';
import styles from './index.module.less';
import { browser, vaildMusicScoreUrl } from '@/helpers/utils';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import { useRouter } from 'vue-router';
import MSearch from '@/components/m-search';
import { Cell, Image, List, Popup } from 'vant';
import iconPlayer from './images/icon-player.png';
import iconFire from './images/icon-fire.png';
import { api_musicSheetCategoriesPage, api_musicSheetPage } from '../co-ai/api';
import { state as baseState } from '@/state';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';
import { postMessage } from '@/helpers/native-message';
import { audioPlayType } from '@/helpers/constant';

const ChildNodeSearch = defineComponent({
  name: 'ChildNodeSearch',
  props: {
    activeRow: {
      type: Object,
      default: () => ({})
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  emits: ['selectChildTag'],
  setup(props, { emit }) {
    const { activeRow } = toRefs(props);
    const selectItem = ref({});

    watch(
      () => props.activeRow,
      () => {
        activeRow.value = props.activeRow;
        selectItem.value = {};
      }
    );
    return () => (
      <>
        {activeRow.value?.id && (
          <>
            <div class={styles.title}>{activeRow.value.columnName}</div>
            <div class={[styles.subjectContainer]}>
              {activeRow.value?.children.map((subject: any) => (
                <div
                  class={[
                    styles.subjectItem,
                    (activeRow.value.activeIndex || '') == subject.id &&
                      styles.active
                  ]}
                  onClick={() => {
                    activeRow.value.activeIndex = subject.id;
                    let children: any;
                    let columnName = '';
                    if (subject.children) {
                      children = [
                        {
                          columnName: subject.children[0].columnName,
                          name: '全部',
                          id: ''
                        },
                        ...subject.children
                      ];
                      columnName = subject.children[0].columnName;

                      selectItem.value = {
                        ...subject,
                        columnName,
                        activeIndex: '',
                        children
                      };
                    } else {
                      selectItem.value = {};
                    }
                    emit('selectChildTag', activeRow.value.activeIndex);
                  }}>
                  {subject.name}
                </div>
              ))}
            </div>

            <ChildNodeSearch
              activeRow={selectItem.value}
              onSelectChildTag={(item: any) => {
                emit('selectChildTag', item || activeRow.value.activeIndex);
              }}
            />
          </>
        )}
      </>
    );
  }
});

export default defineComponent({
  name: 'hot-music-more',
  setup() {
    const router = useRouter();
    const state = reactive({
      background: 'transparent',
      loading: false,
      finished: false,
      searchPopup: false,
      musicTagList: [] as any,
      gradeList: [] as any,
      musicCategory: [] as any,
      musics: [] as any,
      types: [] as any,
      subjectList: [] as any,
      audioPlayTypeList: [] as any, // 场景
      sAPT: '', // 场景
      sMSCI: '',
      sMII: '',
      sBookId: '' as any,
      sGrade: '' as any
    });

    const musicForms = reactive({
      page: 1,
      rows: 20,
      status: 1,
      sortType: 2, // 默认热度排序
      keyword: '', // 关键词
      grade: '',
      audioPlayTypes: [] as any,
      bookVersionId: null as any,
      musicSheetCategoriesId: '',
      musicalInstrumentId: ''
    });

    const data = reactive({
      selectParents: {}, // 选中的数据
      tags: [] as any[],
      tagActiveId: '' as any,
      tagActive: {} as any,
      childSelectId: null as any
    });
    let isClick = false
    const getMusicList = async () => {
      if (isClick) return;
      isClick = true;
      state.loading = true;
      try {
        const res = await api_musicSheetPage({
          ...musicForms
        });
        if (res.code === 200 && Array.isArray(res?.data?.rows)) {
          const result = res.data.rows || [];
          result.forEach((item: any) => {
            item.audioPlayTypeArray = item.audioPlayTypes
              ? item.audioPlayTypes.split(',')
              : [];
          });
          state.musics = [...state.musics, ...res.data.rows];
          state.finished = !res.data.next;
          musicForms.page = res.data.current + 1;
          // state.listState.dataShow = state.list.length > 0;
        } else {
          state.finished = true;
        }
      } catch (error) {
        // console.log('🚀 ~ error:', error);
        state.finished = true;
      }
      state.loading = false;
      isClick = false
    };

    const getSubjecList = async () => {
      try {
        let subjectIds = baseState.user.data?.subjectId || '';
        subjectIds = subjectIds.split(',');
        const subjectId = subjectIds[0] || '';
        const res = await request.post('/edu-app/subject/list', {
          enableFlag: true,
          delFlag: 0,
          page: 1,
          subjectId: subjectId || '',
          rows: 999
        });

        if (subjectId) {
          const result = res.data || [];
          const tempSubjects: any = [];
          result.forEach((item: any) => {
            const instruments = item.instruments || [];
            if (Number(subjectId) === item.id && instruments.length > 0) {
              instruments.forEach((child: any, index: number) => {
                tempSubjects.push({
                  text: child.name,
                  value: child.id,
                  className: index === 0 ? 'selected' : ''
                });
              });
            }
          });

          if (tempSubjects.length > 0) {
            state.subjectList = [{ text: '全部', value: '' }, ...tempSubjects];
            // musicForms.musicalInstrumentId = tempSubjects[0].value;
          }
        }
        // console.log(state.subjectList, state.subjectItem);
      } catch {
        //
      }
    };

    /** 获取音乐教材列表 */
    const getMusicSheetCategories = async () => {
      try {
        // let subjectIds = baseState.user.data?.subjectId || '';
        // subjectIds = subjectIds.split(',');
        // const subjectId = subjectIds[0] || '';
        const res = await api_musicSheetCategoriesPage({
          page: 1,
          rows: 999,
          enable: true
          // subjectId: subjectId
          // musicTagIds: route.query.musicTagId ? [route.query.musicTagId] : []
        });
        if (res.code === 200 && Array.isArray(res?.data?.rows)) {
          const temp: any = [];
          res.data.rows.forEach((item: any) => {
            temp.push({
              value: item.id,
              text: item.name
            });
          });
          state.types = temp;
        }
      } catch (error) {
        console.log('🚀 ~ error:', error);
      }
    };

    const onDetail = (item: any) => {
      const src = `${vaildMusicScoreUrl()}/instrument/?id=${
        item?.id
      }&showGuide=true&modelType=practise`;

      // if (item.paymentType === 'FREE') {
      //   src += `&showCourseMember=true`;
      // }
      postMessage({
        api: 'openAccompanyWebView',
        content: {
          url: src,
          orientation: 0,
          isHideTitle: true,
          statusBarTextColor: false,
          isOpenLight: true,
          c_orientation: 0 // 0 横屏 1 竖屏
        }
      });
    };
    const getMusicTagTree = async () => {
      try {
        const res = await request.get('/edu-app/musicTag/tree');
        const result = res.data || [];
        data.tags = [
          {
            columnName: result[0].columnName,
            name: '全部',
            id: ''
          },
          ...result
        ];
        data.tagActiveId = data.tags[0].id;
        // result.forEach((item: any) => {
        //   if (item.children && item.children.length > 0) {
        //     item.children.forEach((child: any) => {
        //       child.children = child.categoriesList || [];
        //     });
        //   }
        // });
        // state.musicTagList = result;
        // if (result.length > 0) {
        //   musicForms.bookVersionId = result[0].id;
        //   onChangeSearch('version', result[0].children);
        // }
      } catch {
        //
      }
    };

    const changeTag = (item: any) => {
      data.tagActiveId = item.id;
      data.childSelectId = null;
      let children: any;
      let columnName = '';
      console.log(item, 'item');
      if (item.children) {
        children = [
          {
            columnName: item.children[0].columnName,
            name: '全部',
            id: ''
          },
          ...item.children
        ];
        columnName = item.children[0].columnName;
        data.selectParents = {
          ...item,
          columnName,
          activeIndex: '',
          children
        };
      } else {
        data.selectParents = {};
      }

      // onSearch();
    };

    const formatUsedNum = (num: number) => {
      if (num < 10000) {
        return num;
      } else {
        const n = num / 10000;
        return Number(n.toFixed(1)) + '万';
      }
    };

    // 判断是否有数据
    const isSearch = computed(() => {
      return data.tags.length > 0 ? true : false;
    });

    onMounted(async () => {
      // 场景
      const tempAudio = Object.keys(audioPlayType).map(key => {
        return {
          id: key,
          name: audioPlayType[key]
        };
      });
      state.audioPlayTypeList = [{ name: '全部', id: '' }, ...tempAudio];

      state.loading = true;
      // await getSubjecList();
      // await getMusicSheetCategories();
      await getMusicTagTree();
      getMusicList();
    });
    return () => (
      // sortType： 2
      <div
        class={[
          styles.hotMusicMore,
          browser().isTablet ? styles.hotMusicMoreTablet : ''
        ]}>
        <MSticky position="top">
          <MHeader border={false} background={'transparent'}>
            {{
              content: () => (
                <div class={styles.woringHeader}>
                  <i
                    onClick={() => {
                      if (browser().isApp) {
                        postMessage({
                          api: 'goBack'
                        });
                      } else {
                        router.back();
                      }
                    }}
                    class={[
                      'van-badge__wrapper van-icon van-icon-arrow-left van-nav-bar__arrow',
                      styles.leftArrow
                    ]}></i>
                  <span class={styles.title}>
                    <i></i>
                  </span>
                </div>
              )
            }}
          </MHeader>

          <MSearch
            // background={state.background}
            background={'transparent'}
            onSearch={(val: any) => {
              musicForms.keyword = val;
              musicForms.page = 1;
              state.musics = [];
              state.finished = false;
              getMusicList();
            }}>
            {{
              left: () => (
                // 由于添加了场景，必然有搜索条件
                // isSearch.value && (
                <div
                  class={[
                    styles.searchContent,
                    state.searchPopup && styles.active
                  ]}
                  onClick={() => {
                    state.sBookId = musicForms.bookVersionId;
                    state.sAPT =
                      musicForms.audioPlayTypes.length > 1
                        ? 'PLAY_SING'
                        : musicForms.audioPlayTypes.join('');
                    state.searchPopup = true;
                  }}>
                  <span>筛选</span>
                  <i></i>
                </div>
              )
              // )
            }}
          </MSearch>
        </MSticky>

        <List
          loading={state.loading}
          finished={state.finished}
          finishedText=" "
          onLoad={getMusicList}
          immediateCheck={false}>
          {state.musics.length > 0 && (
            <div class={styles.musicListSection}>
              <div class={styles.musicList}>
              {state.musics.map((item: any) => (
                <Cell
                  class={styles.musicItem}
                  border={false}
                  center
                  onClick={() => onDetail(item)}>
                  {{
                    icon: () => (
                      <div class={styles.musicImg}>
                        <i
                          class={[
                            styles.iconType,
                            styles[item.paymentType]
                          ]}></i>
                        <Image class={styles.musicImg} src={item.titleImg} />
                      </div>
                    ),
                    title: () => (
                      <div class={styles.musicContnet}>
                        <h2>{item.musicSheetName}</h2>
                        <div class={styles.allStatus}>
                          <span class={styles.hotNum}>
                            <img src={iconFire} class={styles.iconFire} />
                            {formatUsedNum(item.usedNum)}
                          </span>
                          {item.audioPlayTypes?.includes('SING') && (
                            <span
                              class={[styles.iconPlayType, styles.iconSing]}>
                              演唱
                            </span>
                          )}
                          {item.audioPlayTypes?.includes('PLAY') && (
                            <span
                              class={[styles.iconPlayType, styles.iconPlay]}>
                              演奏
                            </span>
                          )}

                          {item.composer && <p>{item.composer}</p>}
                        </div>
                      </div>
                    ),
                    'right-icon': () => (
                      <Image class={styles.musicPlayIcon} src={iconPlayer} />
                    )
                  }}
                </Cell>
              ))}
            </div>
            </div>
          )}
        </List>

        {!state.loading && state.musics.length === 0 && (
          <div class={styles.emptyGroup}>
            <MEmpty description="暂无曲谱" />
          </div>
        )}

        <Popup position="bottom" round v-model:show={state.searchPopup}>
          <div class={styles.searchContainer}>
            <div class={styles.searchHead}>
              <span
                class={styles.cancel}
                onClick={() => (state.searchPopup = false)}>
                取消
              </span>
              <span>筛选</span>
              <span
                class={styles.confirm}
                onClick={() => {
                  // musicForms.musicSheetCategoriesId = state.sMSCI;
                  // musicForms.musicalInstrumentId = state.sMII;
                  musicForms.bookVersionId =
                    data.childSelectId || data.tagActiveId;
                  // musicForms.grade = state.sGrade;
                  musicForms.audioPlayTypes = state.sAPT
                    ? state.sAPT === 'PLAY_SING'
                      ? ['SING', 'PLAY']
                      : [state.sAPT]
                    : [];
                  state.searchPopup = false;
                  musicForms.page = 1;
                  state.musics = [];
                  state.finished = false;
                  getMusicList();
                }}>
                确定
              </span>
            </div>

            <div class={styles.changeSubjectContainer}>
              {state.audioPlayTypeList.length > 0 && (
                <>
                  <div class={styles.title}>场景</div>
                  <div class={styles.subjectContainer}>
                    {state.audioPlayTypeList.map((subject: any) => (
                      <div
                        class={[
                          styles.subjectItem,
                          subject.id === state.sAPT && styles.active
                        ]}
                        onClick={() => {
                          state.sAPT = subject.id;
                        }}>
                        {subject.name}
                      </div>
                    ))}
                  </div>
                </>
              )}

              {data.tags.length > 0 && (
                <>
                  <div class={styles.title}>{data.tags[0]?.columnName}</div>
                  <div class={styles.subjectContainer}>
                    {data.tags.map((subject: any) => (
                      <div
                        class={[
                          styles.subjectItem,
                          (subject.id || '') === (data.tagActiveId || '') &&
                            styles.active
                        ]}
                        onClick={() => {
                          changeTag(subject);
                        }}>
                        {subject.name}
                      </div>
                    ))}
                  </div>
                  <ChildNodeSearch
                    activeRow={data.selectParents}
                    onSelectChildTag={(val: any) => {
                      data.childSelectId = val;
                      // onSearch();
                      console.log(data.childSelectId);
                    }}
                  />
                </>
              )}

              {/* {state.gradeList.length > 0 && (
                <>
                  <div class={styles.title}>年级</div>
                  <div class={styles.subjectContainer}>
                    {state.gradeList.map((subject: any) => (
                      <div
                        class={[
                          styles.subjectItem,
                          subject.id === state.sGrade && styles.active
                        ]}
                        onClick={() => {
                          state.sGrade = subject.id;
                          onChangeSearch('grade', subject.children, true);
                        }}>
                        {subject.name}
                      </div>
                    ))}
                  </div>
                </>
              )}

              {state.musicCategory.length > 0 && (
                <>
                  <div class={styles.title}>曲谱教材</div>
                  <div
                    class={[
                      styles.subjectContainer,
                      styles.subjectContainerTwo
                    ]}>
                    {state.musicCategory.map((item: any) => (
                      <div
                        class={[
                          styles.subjectItem,
                          item.id === state.sMSCI && styles.active
                        ]}
                        onClick={() => {
                          state.sMSCI = item.id;
                        }}>
                        {item.name}
                      </div>
                    ))}
                  </div>
                </>
              )} */}
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
