import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui';
import {
  bookVersionPage,
  courseScheduleStart,
  lessonCoursewarePage,
  queryCourseware
} from '@/views/prepare-lessons/api';
import { useRouter } from 'vue-router';
import { useThrottleFn } from '@vueuse/core';
import { getCourseChapter } from '../api';
import { useCatchStore } from '/src/store/modules/catchData';
export default defineComponent({
  name: 'goto-class',
  emits: ['close', 'preview'],
  props: {
    activeRow: {
      type: Object,
      default: () => ({ id: '', currentGradeNum: '' })
    }
  },
  setup(props, { emit }) {
    // 'practice' | 'evaluation'
    const forms = reactive({
      bookVersionId: null,
      classGroupId: null,
      category: null,
      chapter: null,
      subjectId: null,
      musicTagList: [] as any,
      loading: false,
      list: [] as any,
      chapterList: [] as any,
      unit: null,
      unitList: [],
      subjectList: [] as any
    });
    const router = useRouter();
    const catchStore = useCatchStore();
    const message = useMessage();
    const gotoClassPage = () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return;
        const { data } = await queryCourseware({
          coursewareDetailKnowledgeId: forms.chapter,
          subjectId: forms.subjectId,
          page: 1,
          rows: 99
        });
        if (data.rows && data.rows.length > 0) {
          const res = await courseScheduleStart({
            lessonCoursewareKnowledgeDetailId: forms.chapter,
            classGroupId: props.activeRow.id,
            subjectId: forms.subjectId
          });

          emit('close');
          emit('preview', {
            type: 'class',
            classId: res.data, // 上课编号
            lessonCourseId: forms.category,
            classGroupId: props.activeRow.id,
            subjectId: forms.subjectId,
            detailId: forms.chapter
          });
        } else {
          message.error('当前章节暂无课件，请重新选择');
        }
      });

      /**
       *         query: {
            type: 'class',
            classGroupId: item.id,
            subjectId: prepareStore.getSubjectId,
            detailId: prepareStore.getSelectKey // 章节id
          }
       */
    };

    const formsRef = ref();
    const throttledFn = useThrottleFn(() => getLessonCourseware(), 500);
    const getLessonCourseware = async () => {
      forms.category = null;
      forms.unit = null;
      forms.category = null;
      forms.chapter = null;
      forms.loading = true;

      if (forms.bookVersionId) {
        try {
          const { data } = await lessonCoursewarePage({
            page: 1,
            rows: 99,
            type: 'COURSEWARE',
            enableFlag: 1,
            bookVersionId: forms.bookVersionId
            // currentGradeNum: props.activeRow.currentGradeNum
          });

          forms.list = data.rows.map((item: any) => {
            return {
              label: item.name,
              value: item.id
            };
          });
        } catch {
          //
        }
      } else {
        forms.list = [];
      }

      forms.loading = false;
    };
    const getVersion = async () => {
      forms.unit = null;
      forms.chapter = null;

      try {
        const { data } = await bookVersionPage({
          page: 1,
          rows: 99,
          type: 'COURSEWARE'
        });
        const temp = data.rows || [];
        temp.forEach((item: any) => {
          forms.musicTagList.push({
            id: item.id,
            name: item.name
          });
        });
      } catch {
        //
      }
    };

    const getunitList = async () => {
      forms.unit = null;
      forms.chapter = null;
      try {
        if (forms.category) {
          const res = await getCourseChapter(forms.category);
          forms.unitList = res.data.lessonList.map((item: any) => {
            return { ...item, label: item.name, value: item.id };
          });
        } else {
          forms.unitList = [];
        }
      } catch (e) {
        console.log(e);
      }
    };
    const getchapterList = () => {
      forms.chapter = null;
      if (forms.unit) {
        const item: any = forms.unitList.find((item: any) => {
          return item.id === forms.unit;
        });
        forms.chapterList = item.knowledgeList.map((know: any) => {
          return { ...know, label: know.name, value: know.id };
        });
        console.log('getchapterList', item);
      } else {
        forms.chapterList = [];
      }
      console.log('getchapterList');
    };
    onMounted(async () => {
      await catchStore.getSubjects();
      forms.subjectList = catchStore.getSubjectList.map((item: any) => {
        return {
          label: item.name,
          value: item.id
        };
      });
      getVersion();
    });
    return () => (
      <div class={styles.trainUpdate}>
        <NForm
          labelAlign="left"
          labelPlacement="left"
          ref={formsRef}
          model={forms}>
          <NFormItem
            path="bookVersionId"
            rule={[{ required: true, message: '选择教材版本' }]}>
            <NSelect
              placeholder="选择教材版本"
              clearable
              options={[...forms.musicTagList]}
              labelField="name"
              valueField="id"
              v-model:value={forms.bookVersionId}
              onUpdate:value={() => throttledFn()}
            />
          </NFormItem>
          <NFormItem
            path="category"
            rule={[{ required: true, message: '请选择册别' }]}>
            <NSelect
              {...({
                options: [...forms.list],
                placeholder: '选择册别',
                clearable: true
              } as any)}
              disabled={!forms.bookVersionId}
              v-model:value={forms.category}
              onUpdate:value={() => getunitList()}></NSelect>
          </NFormItem>
          <NFormItem
            path="unit"
            rule={[{ required: true, message: '请选择单元' }]}>
            <NSelect
              disabled={!forms.category}
              {...({
                options: [...forms.unitList],
                placeholder: '选择单元',
                clearable: true
              } as any)}
              v-model:value={forms.unit}
              onUpdate:value={() => getchapterList()}></NSelect>
          </NFormItem>
          <NFormItem
            path="chapter"
            rule={[{ required: true, message: '请选择章节' }]}>
            <NSelect
              disabled={!forms.unit}
              {...({
                options: [...forms.chapterList],
                placeholder: '选择章节',
                clearable: true
              } as any)}
              v-model:value={forms.chapter}></NSelect>
          </NFormItem>
          <NFormItem
            path="subjectId"
            rule={[{ required: true, message: '请选择乐器' }]}>
            <NSelect
              {...({
                options: [...forms.subjectList],
                placeholder: '选择乐器',
                clearable: true
              } as any)}
              v-model:value={forms.subjectId}></NSelect>
          </NFormItem>
          <NSpace class={styles.updateBtnGroup}>
            <NButton strong type="default" round onClick={() => emit('close')}>
              取消
            </NButton>
            <NButton
              strong
              type="primary"
              round
              onClick={() => gotoClassPage()}>
              确认
            </NButton>
          </NSpace>
        </NForm>
      </div>
    );
  }
});
