import { defineComponent, onMounted, reactive, watch } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NModal,
  NScrollbar,
  NSelect,
  NSpace,
  NSpin,
  useMessage,
  useDialog
} from 'naive-ui';
import CardType from '/src/components/card-type';
import AttendClass from '/src/views/prepare-lessons/model/attend-class';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { useCatchStore } from '/src/store/modules/catchData';
import TheEmpty from '/src/components/TheEmpty';
import { queryCourseware, saveCourseware } from '../../../api';
import Draggable from 'vuedraggable';
import iconDelete from '../../../images/icon-delete.png';
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'courseware-modal',
  setup() {
    const catchStore = useCatchStore();
    const prepareStore = usePrepareStore();
    const router = useRouter();
    const dialog = useDialog();
    const message = useMessage();
    const forms = reactive({
      coursewareList: [] as any,
      loadingStatus: false,
      showAttendClass: false,
      drag: false
    });

    // 获取列表
    const getList = async () => {
      forms.loadingStatus = true;
      try {
        // 判断是否有选择对应的课件
        if (!prepareStore.getSelectKey) return;
        const { data } = await queryCourseware({
          coursewareDetailKnowledgeId: prepareStore.getSelectKey,
          subjectId: prepareStore.getSubjectId,
          pag: 1,
          rows: 99
        });
        const tempRows = data.rows || [];
        const temp: any = [];
        tempRows.forEach((row: any) => {
          temp.push({
            id: row.id,
            materialId: row.materialId,
            coverImg: row.coverImg,
            type: row.materialType,
            title: row.materialName,
            isCollect: !!row.favoriteFlag,
            isSelected: row.source === 'PLATFORM' ? true : false,
            content: row.content
          });
        });

        forms.coursewareList = temp || [];
        prepareStore.setCoursewareList(temp || []);
      } catch {
        //
      }
      forms.loadingStatus = false;
    };

    // 监听选择的key 左侧选择了其它的课
    watch(
      () => prepareStore.getSelectKey,
      () => {
        getList();
      }
    );
    watch(
      () => prepareStore.getIsAddResource,
      (val: boolean) => {
        if (val) {
          getList();
          prepareStore.setIsAddResource(false);
        }
      }
    );

    // 删除
    const onDelete = (item: any) => {
      //
      const index = forms.coursewareList.findIndex(
        (c: any) => c.id === item.id
      );
      forms.coursewareList.splice(index, 1);
      prepareStore.setCoursewareList(forms.coursewareList);
    };

    // 完成编辑
    const onOverEdit = async () => {
      dialog.warning({
        title: '提示',
        content: `是否完成编辑？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            const temp: any = [];
            forms.coursewareList.forEach((item: any) => {
              temp.push({
                materialName: item.title,
                materialType: item.type,
                materialId: item.materialId,
                id: item.id
              });
            });
            // 保存课件
            await saveCourseware({
              coursewareDetailKnowledgeId: prepareStore.getSelectKey,
              lessonCoursewareId: prepareStore.getLessonCoursewareId,
              lessonCoursewareDetailId:
                prepareStore.getLessonCoursewareDetailId,
              materialList: [...temp]
            });

            forms.drag = false;
            message.success('编辑成功');

            prepareStore.setCoursewareList(forms.coursewareList);
          } catch {
            //
          }
        }
      });
    };

    // 预览上课
    const onPreviewAttend = () => {
      const { href } = router.resolve({
        path: '/attend-class',
        query: {
          type: 'preview',
          subjectId: prepareStore.getSubjectId,
          detailId: prepareStore.getSelectKey
        }
      });
      window.open(href, +new Date() + '');
    };

    onMounted(async () => {
      // 获取教材分类列表
      await catchStore.getSubjects();

      const subjectList = catchStore.getSubjectList;
      if (subjectList.length > 0) {
        prepareStore.setSubjectId(subjectList[0].id);
      }

      await getList();
    });

    return () => (
      <div class={styles.coursewareModal}>
        <div class={styles.btnGroup}>
          {forms.drag ? (
            <NSpace>
              <NButton type="default" onClick={onOverEdit}>
                完成编辑
              </NButton>
              <NButton
                type="error"
                onClick={() => {
                  forms.drag = false;
                  getList();
                }}>
                退出编辑
              </NButton>
              <NButton
                type="error"
                onClick={() => {
                  forms.coursewareList = [];
                  prepareStore.setCoursewareList([]);
                }}>
                清空资源
              </NButton>
              <span class={styles.tips}>拖动可将资源进行排序</span>
            </NSpace>
          ) : (
            <NSpace>
              <NSelect
                placeholder="选择声部"
                options={catchStore.getSubjectList}
                labelField="name"
                valueField="id"
                value={prepareStore.getSubjectId}
                onUpdate:value={(val: any) => {
                  prepareStore.setSubjectId(val);
                  getList();
                }}
              />
              <NButton type="default" onClick={() => (forms.drag = true)}>
                编辑
              </NButton>
            </NSpace>
          )}

          <NSpace>
            <NButton type="default" onClick={onPreviewAttend}>
              预览
            </NButton>
            <NButton
              type="primary"
              onClick={() => (forms.showAttendClass = true)}>
              开始上课
            </NButton>
          </NSpace>
        </div>

        <NScrollbar class={styles.listContainer}>
          <NSpin show={forms.loadingStatus}>
            <div
              class={[
                styles.listSection,
                !forms.loadingStatus &&
                prepareStore.getCoursewareList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {forms.coursewareList.length > 0 && (
                <>
                  {forms.drag ? (
                    <Draggable
                      v-model:modelValue={forms.coursewareList}
                      itemKey="id"
                      componentData={{
                        animation: 200,
                        group: 'description'
                      }}
                      class={styles.list}>
                      {{
                        item: (element: any) => {
                          const item = element.element;
                          return (
                            <div
                              data-id={item.id}
                              class={[styles.itemBlock, 'row-nav']}>
                              <CardType
                                class={[styles.itemContent, 'handle']}
                                isShowCollect={false}
                                item={item}
                              />
                              <div class={styles.itemOperation}>
                                <img
                                  src={iconDelete}
                                  class={styles.iconDelete}
                                  onClick={(e: MouseEvent) => {
                                    e.stopPropagation();
                                    onDelete(item);
                                  }}
                                />
                              </div>
                            </div>
                          );
                        }
                      }}
                    </Draggable>
                  ) : (
                    <div class={styles.list}>
                      {forms.coursewareList.map((item: any) => (
                        <CardType
                          class={[styles.itemContent, 'handle']}
                          isShowCollect={false}
                          item={item}
                        />
                      ))}
                    </div>
                  )}
                </>
              )}

              {!forms.loadingStatus &&
                prepareStore.getCoursewareList.length <= 0 && (
                  <TheEmpty description="暂无课件" />
                )}
            </div>
          </NSpin>
        </NScrollbar>

        <NModal
          v-model:show={forms.showAttendClass}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal]}
          title={'选择班级'}
          blockScroll={false}>
          <AttendClass onClose={() => (forms.showAttendClass = false)} />
        </NModal>
      </div>
    );
  }
});
