import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NImage,
  NInput,
  NModal,
  NScrollbar,
  NSelect,
  NSpace,
  NSpin,
  useDialog,
  useMessage
} from 'naive-ui';
import AddTeaching, {
  BOOK_DATA
} from '/src/views/natural-resources/model/add-teaching';
import {
  lessonCoursewarePage,
  lessonCoursewareRemove,
  musicTagTree
} from '../../../api';
import iconUploadBg from '../images/icon-upload-bg.svg';
import { useCatchStore } from '/src/store/modules/catchData';
import { useThrottleFn } from '@vueuse/core';

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: null
      // bookType: null
    });

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

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

    // 删除教材
    const onDelete = async (item: any) => {
      dialog.warning({
        title: '提示',
        content: '是否删除该教材?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await lessonCoursewareRemove({ id: item.id });
            message.success('删除成功');
          } catch {
            //
          }
        }
      });
    };

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

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

    onMounted(async () => {
      // 获取教材分类列表
      try {
        const { data } = await musicTagTree({});
        console.log(data);
        const temp = data || [];
        temp.forEach((item: any) => {
          forms.musicTagList.push({
            id: item.id,
            name: item.name
          });
        });
      } catch {
        //
      }
      getLessonCourseware();
    });
    return () => (
      <div class={styles.selectLessonware}>
        <div class={styles.attendClassSearch}>
          <NInput
            placeholder="请输入教材名称"
            clearable
            v-model:value={forms.keyword}
            onKeyup={(e: KeyboardEvent) => {
              if (e.code === 'Enter') {
                throttledFn();
              }
            }}
            onClear={() => throttledFn()}>
            {{
              prefix: () => (
                <span
                  class="icon-search-input"
                  onClick={() => throttledFn()}></span>
              )
            }}
          </NInput>
          <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>
        <NScrollbar class={styles.classList}>
          <NSpin show={forms.loading} class={styles.content}>
            <NSpace size={[50, 40]}>
              <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 => {
                        (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 => {
                            (e.target as any).dataset.loaded = 'true';
                          }}
                        />
                        {item.customFlag && (
                          <>
                            <div class={styles.iconCustom}></div>
                            <div class={styles.editContainer}>
                              <div class={styles.editBtnGroup}>
                                <NButton
                                  size="small"
                                  class={styles.delBtn}
                                  color="#EA4132"
                                  onClick={(e: MouseEvent) => {
                                    e.stopPropagation();
                                    onDelete(item);
                                  }}>
                                  删除
                                </NButton>
                                <NButton
                                  size="small"
                                  class={styles.editBtn}
                                  color="#FFFFFF"
                                  onClick={(e: MouseEvent) => {
                                    e.stopPropagation();
                                    forms.selectItem = item;
                                    forms.teachingStatus = true;
                                  }}>
                                  编辑
                                </NButton>
                              </div>
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                    <div class={styles.itemName}>{item.name}</div>
                  </div>
                );
              })}
            </NSpace>
          </NSpin>
        </NScrollbar>

        {/* 添加自定义教材 */}
        <NModal
          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>
      </div>
    );
  }
});
