import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NCascader,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NModal,
  NPopselect,
  NScrollbar,
  NSelect,
  NSpace,
  NSpin,
  useDialog,
  useMessage
} from 'naive-ui';
import AddTeaching, {
  BOOK_DATA
} from '/src/views/natural-resources/model/add-teaching';
import {
  lessonCoursewarePage,
  lessonCoursewareRemove,
  api_lessonCoursewareTeacherCategory
} from '../../../api';
import iconUploadBg from '../images/icon-upload-bg.png';
import { useCatchStore } from '/src/store/modules/catchData';
import { useThrottleFn } from '@vueuse/core';
import iconEdit from '../images/icon-edit.png';
import iconDelete from '../images/icon-delete.png';
import { modalClickMask } from '/src/state';

export default defineComponent({
  name: 'select-lessonware',
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const dialog = useDialog();
    const message = useMessage();
    const forms = reactive({
      loading: false,
      list: [] as any[],
      teachingStatus: false,
      musicTagList: [] as any[],
      selectItem: {} as any,
      bookVersionId: null,
      keyword: null,
      currentGradeNum: '' as any,
      instrumentId: '' as any,
      removeVisiable: false,
      removeRow: {} as any,
      bookType: '' as any
    });

    const treeList = reactive({
      tempSubjectId: null,
      versionList: [] as any, // 教材
      gradeList: [] as any, // 年级
      bookTypeList: [] as any // 册别
    });

    const getLessonCourseware = async () => {
      forms.loading = true;
      try {
        console.log(forms.bookVersionId, 'bookVersionId')
        const { data } = await lessonCoursewarePage({
          page: 1,
          rows: 99,
          type: 'COURSEWARE',
          enableFlag: 1,
          bookVersionId: forms.bookVersionId === '0' ? null : forms.bookVersionId,
          customFlag: forms.bookVersionId === '0' ? true : null,
          keyword: forms.keyword,
          currentGradeNum: forms.currentGradeNum,
          instrumentId: forms.instrumentId,
          bookType: forms.bookType
        });

        forms.list = data.rows;
      } catch {
        //
      }
      forms.loading = false;
    };

    // 删除教材
    const onDelete = async (item: any) => {
      try {
        await lessonCoursewareRemove({ id: forms.removeRow.id });
        message.success('删除成功');
        getLessonCourseware();
        forms.removeVisiable = false;
      } catch (e) {
        console.log(e);
      }
    };

    const throttledFn = useThrottleFn(() => getLessonCourseware(), 500);

    const onDetail = (item: any) => {
      emit('confirm', item);
      emit('close');
    };

    const getSearchDetail = async () => {
      try {
        const { data } = await api_lessonCoursewareTeacherCategory();

        const result = data || []

        treeList.versionList = [{
          name: '全部',
          id: ''
        }, ...result]
      } catch {
        //
      }
    };

    const selectChildObj = (item: any) => {
      const obj: any = {};
      item?.forEach((child: any) => {
        if (child.id === forms.instrumentId) {
          obj.selected = true;
          obj.name = child.name;
        }
      });
      return obj;
    };

    onMounted(async () => {
      // 获取教材分类列表
      try {
        await catchStore.getSubjects();
        // 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
        //   });
        // });
        await getSearchDetail();
      } catch {
        //
      }
      getLessonCourseware();
    });
    return () => (
      <div class={styles.selectLessonware}>
        <NScrollbar class={styles.classList}>
          <div class={styles.attendClassSearch}>
            <NForm labelAlign="left" labelPlacement="left">
              {treeList.versionList.length > 0 && <NFormItem label="教程：">
                <NSpace class={styles.spaceSection}>
                  {treeList.versionList?.map((subject: any) => (
                    <span
                      class={[
                        styles.textBtn,
                        (forms.bookVersionId || '') ==
                          subject.id && styles.textBtnActive
                      ]}
                      onClick={() => {
                        treeList.bookTypeList = []
                        forms.currentGradeNum = ''
                        forms.bookType = ''
                        if(subject.children && subject.children.length > 0) {
                          const result = subject.children || []
                          treeList.gradeList =  [{
                            name: '全部',
                            id: ''
                          }, ...result]
                        } else {
                          treeList.gradeList = []
                        }
                        forms.bookVersionId = subject.id

                        throttledFn()
                      }}>
                      {subject.name}
                    </span>
                  ))}
                </NSpace>
              </NFormItem>}

              {treeList.gradeList.length > 0 && <NFormItem label="年级：">
                <NSpace class={styles.spaceSection}>
                  {treeList.gradeList?.map((subject: any) => (
                    <span
                      class={[
                        styles.textBtn,
                        (forms.currentGradeNum || '') == subject.id &&
                          styles.textBtnActive
                      ]}
                      onClick={() => {
                        forms.bookType = ''
                        if(subject.children && subject.children.length > 0) {
                          treeList.bookTypeList = subject.children || []
                          const result = subject.children || []
                          treeList.bookTypeList =  [{
                            name: '全部',
                            id: ''
                          }, ...result]
                        } else {
                          treeList.bookTypeList = []
                        }
                        forms.currentGradeNum = subject.id

                        throttledFn()
                      }}>
                      {subject.name}
                    </span>
                  ))}
                </NSpace>
              </NFormItem>}

              {treeList.bookTypeList.length > 0 && <NFormItem label="册别：">
                <NSpace class={styles.spaceSection}>
                  {treeList.bookTypeList?.map((subject: any) => (
                    <span
                      class={[
                        styles.textBtn,
                        (forms.bookType || '') ==
                          subject.id && styles.textBtnActive
                      ]}
                      onClick={() => {
                        forms.bookType = subject.id

                        throttledFn()
                      }}>
                      {subject.name}
                    </span>
                  ))}
                </NSpace>
              </NFormItem>}


              <NFormItem label="乐器：">
                <NSpace class={styles.spaceSection}>
                  {[
                    { name: '全部乐器', value: '' },
                    ...catchStore.getSubjectInstrumentOnly
                  ].map((subject: any) =>
                    subject.instruments && subject.instruments.length > 1 ? (
                      <NPopselect
                        options={subject.instruments}
                        trigger="hover"
                        scrollable
                        v-model:value={treeList.tempSubjectId}
                        onUpdate:value={() => {
                          forms.instrumentId = treeList.tempSubjectId;
                          throttledFn()
                        }}
                        key={subject.value}
                        class={[styles.popSelect]}>
                        <span
                          class={[
                            styles.textBtn,
                            selectChildObj(subject.instruments).selected &&
                              styles.textBtnActive
                          ]}>
                          {selectChildObj(subject.instruments).name ||
                            subject.name}
                          <i class={styles.iconArrow}></i>
                        </span>
                      </NPopselect>
                    ) : (
                      <span
                        class={[
                          styles.textBtn,
                          forms.instrumentId === subject.value &&
                            styles.textBtnActive
                        ]}
                        onClick={() => {
                          forms.instrumentId = subject.value;
                          treeList.tempSubjectId = null;
                          throttledFn()
                        }}>
                        {subject.name}
                      </span>
                    )
                  )}
                </NSpace>
              </NFormItem>
            </NForm>
            {/* <NInput
            placeholder="请输入教材名称"
            clearable
            v-model:value={forms.keyword}
            onKeyup={(e: KeyboardEvent) => {
              if (e.code === 'Enter') {
                throttledFn();
              }
            }}
            onClear={() => {
              forms.keyword = null;
              throttledFn();
            }}>
            {{
              prefix: () => (
                <span
                  class="icon-search-input"
                  onClick={() => throttledFn()}></span>
              )
            }}
          </NInput>
          <NCascader
            placeholder="请选择乐器"
            v-model:value={forms.instrumentId}
            onUpdate:value={() => throttledFn()}
            options={
              [
                { name: '全部乐器', id: null },
                ...catchStore.getSubjectList
              ] as any
            }
            checkStrategy="child"
            showPath={false}
            childrenField="instruments"
            expandTrigger="hover"
            labelField="name"
            valueField="id"
            clearable
            filterable
            style={{ width: '400px' }}
          />
          <NSelect
            placeholder="全部版本"
            clearable
            options={[{ id: null, name: '全部版本' }, ...forms.musicTagList]}
            labelField="name"
            valueField="id"
            v-model:value={forms.bookVersionId}
            onUpdate:value={() => throttledFn()}
          />
          <NSelect
            placeholder="全部年级"
            options={
              [{ label: '全部年级', value: null }, ...BOOK_DATA.grades] as any
            }
            v-model:value={forms.currentGradeNum}
            clearable
            filterable
            onUpdate:value={() => throttledFn()}
          /> */}
            {/* <NSelect
            placeholder="全部册别"
            options={
              [
                { label: '全部册别', value: null },
                ...BOOK_DATA.bookTypes
              ] as any
            }
            v-model:value={forms.bookType}
            clearable
            onUpdate:value={() => throttledFn()}
          /> */}
          </div>
          <NSpin show={forms.loading} class={styles.content}>
            <NSpace class={styles.teachingSpace}>
              <div
                class={styles.item}
                key={`item--1`}
                onClick={() => {
                  forms.selectItem = {};
                  forms.teachingStatus = true;
                }}>
                <div class={styles.cover}>
                  <div class={styles.itemImg}>
                    <div class={styles.itemBg}></div>
                    <NImage
                      objectFit="cover"
                      src={iconUploadBg}
                      lazy
                      previewDisabled={true}
                      onLoad={(e: any) => {
                        (e.target as any).dataset.loaded = 'true';
                      }}
                    />
                  </div>
                </div>
              </div>
              {forms.list.map((item: any, index: number) => {
                return (
                  <div
                    class={styles.item}
                    key={`item-${index}`}
                    onClick={() => onDetail(item)}>
                    <div class={styles.cover}>
                      <div class={styles.itemImg}>
                        <div class={styles.itemBg}></div>
                        <NImage
                          objectFit="cover"
                          src={item.coverImg}
                          lazy
                          previewDisabled={true}
                          onLoad={(e: any) => {
                            (e.target as any).dataset.loaded = 'true';
                          }}
                        />
                        {item.customFlag && (
                          <>
                            <div class={styles.iconCustom}></div>
                            <div class={styles.editContainer}>
                              <div class={styles.editBtnGroup}>
                                <img
                                  src={iconEdit}
                                  class={styles.imgBtn}
                                  onClick={(e: MouseEvent) => {
                                    e.stopPropagation();
                                    forms.selectItem = item;
                                    forms.teachingStatus = true;
                                  }}
                                />
                                <img
                                  src={iconDelete}
                                  class={styles.imgBtn}
                                  onClick={(e: MouseEvent) => {
                                    e.stopPropagation();
                                    forms.removeVisiable = true;
                                    forms.removeRow = item;
                                  }}
                                />
                              </div>
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                    <div class={styles.itemName}>{item.name}</div>
                  </div>
                );
              })}
            </NSpace>
          </NSpin>
        </NScrollbar>

        {/* 添加自定义教材 */}
        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.teachingStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.teachingModal]}
          title={'自定义教材'}
          blockScroll={false}>
          <AddTeaching
            item={forms.selectItem}
            onClose={() => (forms.teachingStatus = false)}
            onConfirm={() => {
              getLessonCourseware();
              forms.selectItem = {};
            }}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.removeVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'删除教材'}>
          <div class={styles.studentRemove}>
            <p>是否删除该教材</p>

            <NSpace class={styles.btnGroup} justify="center">
              <NButton round type="primary" onClick={onDelete}>
                确定
              </NButton>
              <NButton round onClick={() => (forms.removeVisiable = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>
      </div>
    );
  }
});
