import MHeader from '@/components/m-header';
import MSearch from '@/components/m-search';
import MSticky from '@/components/m-sticky';
import {
  Button,
  DropdownItem,
  DropdownMenu,
  List,
  Picker
} from 'vant';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import MStudent from '../component/m-student/index';
import Attendance from '../component/Attendance';
import Assignment from '../component/Assignment';
import SkeletionIndex from '../skeletion-index';
import {
  api_cooperationOrganMusicGroupPage,
  api_studentManageCoopSubjectList,
  api_studentManageUserPage
} from '../api';
import MFullRefresh from '@/components/m-full-refresh';
import { IMusicGroup, IStudentManage, ISubject } from '../type';
import MEmpty from '@/components/m-empty';

export default defineComponent({
  name: 'student-manage',
  setup() {
    const fromData = reactive({
      page: 1,
      rows: 20,
      /** 关键词 */
      keyword: '',
      /** 乐团ID */
      musicGroupId: '',
      /** 学生乐团状态 */
      statusList: ['QUIT'],
      /** 声部ID */
      subjectId: '',
      /** 是否会员 */
      vipFlag: ''
    });
    const studentMagege = reactive({
      skelet: true,
      refresh: false,
      loading: false,
      finshed: false,
      list: [] as IStudentManage[],
      musicGroups: [{ text: '全部乐团', value: '' }] as IMusicGroup[],
      musicGroupName: '全部乐团',
      subjects: [{ text: '全部声部', value: '' }] as ISubject[],
      subjectName: '全部声部',
    });
    const musicGroupRef = ref();
    const musicSelectRef = ref();
    const subjectRef = ref();
    const subjectSelectRef = ref();

    /** 获取乐团列表 */
    const getGroups = () => {
      api_cooperationOrganMusicGroupPage().then(res => {
        let data = Array.isArray(res?.data) ? res.data : [];
        if (data.length) {
          data = [{ name: '全部乐团', id: '' }].concat(data);
          studentMagege.musicGroups = data.map((item: any) => {
            return {
              text: item.name,
              value: item.id
            };
          });
        }
      });
    };

    /** 获取声部列表 */
    const getSubjects = () => {
      api_studentManageCoopSubjectList().then(res => {
        let data = Array.isArray(res?.data) ? res.data : [];
        if (data.length) {
          data = [{ name: '全部声部', id: '' }].concat(data);
          studentMagege.subjects = data.map((item: any) => {
            return {
              text: item.name,
              value: item.id
            };
          });
        }
      });
    };

    const getData = async () => {
      studentMagege.loading = true;
      api_studentManageUserPage({
        ...fromData,
        vipFlag:
          fromData.vipFlag === '1'
            ? true
            : fromData.vipFlag === '2'
            ? false
            : ''
      })
        .then(res => {
          if (studentMagege.refresh) {
            studentMagege.list = [];
          }
          const rows: IStudentManage[] = Array.isArray(res?.data?.rows)
            ? res.data.rows
            : [];
          studentMagege.list = studentMagege.list.concat(rows);
          if (!rows.length || rows.length < fromData.rows) {
            studentMagege.finshed = true;
          }
          fromData.page++;
        })
        .catch(() => {
          studentMagege.finshed = true;
        })
        .finally(() => {
          setTimeout(() => {
            studentMagege.loading = false;
            studentMagege.refresh = false;
            studentMagege.skelet = false;
          }, 500);
        });
    };

    const handleSearch = () => {
      fromData.page = 1;
      studentMagege.refresh = true;
      getData();
    };

    onMounted(() => {
      getGroups();
      getSubjects();
    });

    return () => (
      <div class={styles.container}>
        <MSticky position="top">
          <MHeader />
          <MSearch
            placeholder="请输入学员姓名"
            onSearch={value => {
              fromData.keyword = value;
              handleSearch();
            }}
          />
          <DropdownMenu>
            <DropdownItem
              ref={musicGroupRef}
              title={studentMagege.musicGroupName}>
              <Picker
                ref={musicSelectRef}
                showToolbar={false}
                visibleOptionNum={5}
                columns={studentMagege.musicGroups}
              />
              <div class={['btnGroupPopup', 'van-hairline--top']}>
                <Button
                  round
                  onClick={() => {
                    musicGroupRef.value?.toggle(false);
                  }}>
                  取消
                </Button>
                <Button
                  disabled={!studentMagege.musicGroups.length}
                  type="primary"
                  round
                  onClick={() => {
                    musicSelectRef.value?.confirm?.()
                    const option =
                      musicSelectRef.value?.getSelectedOptions?.()?.[0];
                    if (option) {
                      fromData.musicGroupId = option.value;
                      studentMagege.musicGroupName = option.text;
                      handleSearch();
                    }
                    musicGroupRef.value?.toggle(false);
                  }}>
                  确定
                </Button>
              </div>
            </DropdownItem>
            <DropdownItem ref={subjectRef} title={studentMagege.subjectName}>
              <Picker
                ref={subjectSelectRef}
                showToolbar={false}
                visibleOptionNum={5}
                columns={studentMagege.subjects}
              />
              <div class={['btnGroupPopup', 'van-hairline--top']}>
                <Button
                  round
                  onClick={() => {
                    subjectRef.value?.toggle(false);
                  }}>
                  取消
                </Button>
                <Button
                  disabled={!studentMagege.subjects.length}
                  type="primary"
                  round
                  onClick={() => {
                    subjectSelectRef.value?.confirm?.()
                    const option = subjectSelectRef.value?.getSelectedOptions?.()?.[0];
                    console.log(option);
                    fromData.subjectId = option.value;
                    studentMagege.subjectName = option.text;
                    handleSearch();
                    subjectRef.value?.toggle(false);
                  }}>
                  确定
                </Button>
              </div>
            </DropdownItem>
          </DropdownMenu>
        </MSticky>

        <MFullRefresh
          v-model:modelValue={studentMagege.refresh}
          onRefresh={() => {
            fromData.page = 1;
            studentMagege.finshed = false;
            getData();
          }}>
          <List
            class={styles.list}
            loading={studentMagege.loading}
            finished={studentMagege.finshed}
            onLoad={() => {
              studentMagege.loading = true;
              console.log('触底了');
              getData();
            }}>
            <SkeletionIndex loading={studentMagege.skelet}>
              <>
                {studentMagege.list.map((item: IStudentManage) => (
                  <div class={styles.student}>
                    <MStudent item={item} />
                    <Assignment item={item} />
                    <Attendance item={item} />
                  </div>
                ))}

                {!studentMagege.loading && !studentMagege.list.length && (
                  <MEmpty
                    description="暂无数据"
                    style={{
                      minHeight: '100%'
                    }}
                  />
                )}
              </>
            </SkeletionIndex>
          </List>
        </MFullRefresh>
      </div>
    );
  }
});
