import { defineComponent, nextTick, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NImage,
  NInput,
  NModal,
  NScrollbar,
  NSpace,
  NSpin,
  useMessage
} from 'naive-ui';
import add from '@/views/studentList/images/add.png';
import WorkSection from '/src/views/prepare-lessons/model/work-section';
import {
  lessonPreTrainingV2Page,
  lessonPreTrainingV2Save
} from '/src/views/prepare-lessons/api';
import { storeToRefs } from 'pinia';
import { useUserStore } from '/src/store/modules/users';
import AssignHomework from '/src/views/prepare-lessons/components/lesson-main/train/assign-homework';
import Train from '/src/views/prepare-lessons/components/lesson-main/train';
import ResourceMain from '/src/views/prepare-lessons/components/resource-main';
import dayjs from 'dayjs';
import { useResizeObserver } from '@vueuse/core';
import TheEmpty from '/src/components/TheEmpty';
import { modalClickMask } from '/src/state';

export default defineComponent({
  name: 'class-work',
  props: {
    /** 章节编号 */
    detailId: {
      type: String,
      default: ''
    },
    /** 声部编号 */
    subjectId: {
      type: String,
      default: ''
    },
    /** 班级编号 */
    classGroupId: {
      type: String,
      default: ''
    },
    /** 上课编号 */
    courseScheduleId: {
      type: String,
      default: ''
    },
    activeName: {
      type: String,
      default: ''
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const users = useUserStore();
    const { info } = storeToRefs(users);
    const message = useMessage();
    const forms = reactive({
      loadingStatus: false,
      tableList: [] as any,
      editTitleVisiable: false,
      selectItem: {} as any,
      editTitle: '',
      assignHomeworkStatus: false,
      editBtnLoading: false,
      workVisiable: false
    });
    const getList = async () => {
      forms.loadingStatus = true;
      try {
        // 判断是否有选择对应的课件 或声部
        if (!props.detailId) return (forms.loadingStatus = false);
        const { data } = await lessonPreTrainingV2Page({
          page: 1,
          coursewareKnowledgeDetailId: props.detailId
        });
        const result = data.rows || [];
        const tempList: any = [];
        result.forEach((item: any) => {
          const { lessonPreTrainingDetails, ...ies } = item;
          const tList: any = {
            ...ies,
            pTitle: '',
            eTitle: '',
            teacherAvatar: info.value?.avatar,
            teacherName: info.value?.nickname,
            lessonPreTrainingDetails
          };
          lessonPreTrainingDetails.forEach((child: any) => {
            if (child.trainingType === 'PRACTICE' && child.musicName) {
              tList.pTitle += tList.pTitle
                ? '、《' + child.musicName + '》'
                : '练习曲目《' + child.musicName + '》';
            }
            if (child.trainingType === 'EVALUATION' && child.musicName) {
              tList.eTitle += tList.eTitle
                ? '、《' + child.musicName + '》'
                : '评测曲目《' + child.musicName + '》';
            }
          });

          tempList.push(tList);
        });

        forms.tableList = tempList;
      } catch {
        //
      }
      forms.loadingStatus = false;
    };

    /** 修改标题 */
    const onEditTitleSubmit = async () => {
      if (!forms.editTitle) {
        message.error('请输入作业标题');
        return;
      }
      forms.editBtnLoading = true;
      try {
        await lessonPreTrainingV2Save({
          id: forms.selectItem.id,
          title: forms.editTitle
        });
        message.success('修改成功');
        forms.editTitleVisiable = false;
        forms.tableList.forEach((item: any) => {
          if (item.id === forms.selectItem.id) {
            item.title = forms.editTitle;
          }
        });
      } catch {
        //
      }
      forms.editBtnLoading = false;
    };

    const getModalHeight = () => {
      useResizeObserver(
        document.querySelector('#model-homework-height') as HTMLElement,
        (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          document.documentElement.style.setProperty(
            '--window-page-lesson-height',
            height + 'px'
          );
        }
      );
    };

    onMounted(() => {
      getList();
    });
    return () => (
      <div class={styles.classWork}>
        <div class={styles.btnGroup}>
          <NSpace>
            <NButton
              type="primary"
              class={styles.addPreset}
              onClick={() => {
                // 设置右侧栏状态
                forms.workVisiable = true;
                forms.selectItem = {};
                nextTick(() => {
                  getModalHeight();
                });
              }}
              v-slots={{
                icon: () => (
                  <>
                    <NImage
                      class={styles.addBtnIcon}
                      previewDisabled
                      src={add}></NImage>
                  </>
                )
              }}>
              添加作业
            </NButton>
          </NSpace>
        </div>

        <NScrollbar style={{ height: '60vh' }} class={[styles.listContainer]}>
          <NSpin show={forms.loadingStatus}>
            <div
              class={[
                styles.listSection,
                !forms.loadingStatus &&
                  forms.tableList.length <= 0 &&
                  styles.listSectionEmpty
              ]}
              style={{ minHeight: '55vh' }}>
              <NSpace vertical>
                {forms.tableList.map((item: any) => (
                  <WorkSection
                    hideDelete
                    item={item}
                    onEditTitle={() => {
                      forms.selectItem = item;
                      forms.editTitle = item.title;
                      forms.editTitleVisiable = true;
                    }}
                    onEdit={() => {
                      forms.workVisiable = true;
                      forms.selectItem = item;
                      nextTick(() => {
                        getModalHeight();
                      });
                    }}
                    onConfirm={() => {
                      if (
                        !item.lessonPreTrainingDetails ||
                        item.lessonPreTrainingDetails.length <= 0
                      ) {
                        message.error('作业预设不能为空');
                        return;
                      }
                      forms.assignHomeworkStatus = true;
                      forms.selectItem = item;
                    }}
                  />
                ))}
              </NSpace>

              {!forms.loadingStatus && forms.tableList.length <= 0 && (
                <TheEmpty description="暂无作业" />
              )}
            </div>
          </NSpin>
        </NScrollbar>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.editTitleVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'作业重命名'}>
          <div class={styles.studentRemove}>
            <NInput
              placeholder="请输入作业标题"
              v-model:value={forms.editTitle}
              maxlength={100}
              onKeyup={(e: any) => {
                if (e.code === 'ArrowLeft' || e.code === 'ArrowRight') {
                  e.stopPropagation();
                }
              }}
            />

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton round onClick={() => (forms.editTitleVisiable = false)}>
                取消
              </NButton>
              <NButton
                round
                type="primary"
                onClick={onEditTitleSubmit}
                loading={forms.editBtnLoading}>
                确定
              </NButton>
            </NSpace>
          </div>
        </NModal>

        {/* 添加自定义教材 */}
        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.assignHomeworkStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.assignHomework]}
          title={'布置作业'}
          blockScroll={false}>
          <AssignHomework
            classGroupId={props.classGroupId}
            courseScheduleId={props.courseScheduleId}
            item={forms.selectItem}
            trainList={[]}
            onClose={() => (forms.assignHomeworkStatus = false)}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.workVisiable}
          preset="card"
          class={['modalTitle background', styles.workVisiable]}
          title={'作业详情'}>
          <div id="model-homework-height" class={styles.workContainer}>
            <div class={styles.workTrain}>
              <Train
                coursewareKnowledgeDetailId={props.detailId}
                classGroupId={props.classGroupId}
                courseScheduleId={props.courseScheduleId}
                lessonPreTraining={{
                  title:
                    (props.activeName || dayjs().format('YYYY年MM月DD日')) +
                    '-课后作业',
                  id: forms.selectItem.id
                }}
                // cardType={'homeworkRecord'}
                onChange={(val: any) => {
                  forms.workVisiable = val.status;
                  getList();
                }}
              />
            </div>
            <div class={styles.resourceMain}>
              <ResourceMain cardType="homerowk-record" />
            </div>
          </div>
        </NModal>
      </div>
    );
  }
});
