import { defineComponent, reactive, onMounted, ref } from 'vue';
import styles from './index.module.less';
import {
  NAvatar,
  NButton,
  NDivider,
  NForm,
  NFormItem,
  NImage,
  NModal,
  NSpace,
  NSpin,
  NTooltip,
  useMessage
} from 'naive-ui';
import SearchInput from '@/components/searchInput';
import CDatePicker from '/src/components/CDatePicker';
import CSelect from '@/components/CSelect';
import add from '@/views/studentList/images/add.png';
import { useRoute, useRouter } from 'vue-router';
import { getGradeLevelList, getGradeYearList } from '../home/api';
import { initCache, setCache } from '/src/hooks/use-async';
import { classArray, getgradeNumList } from '../classList/contants';
import teacherIcon from '@components/layout/images/teacherIcon.png';
import Pagination from '/src/components/pagination';
import { api_trainingList, api_withdrawTraining } from './api';
import TheEmpty from '/src/components/TheEmpty';
import { fscreen, getTimes } from '/src/utils';
import dayjs from 'dayjs';
import Train from '../prepare-lessons/components/lesson-main/train';
import ResourceMain from '../prepare-lessons/components/resource-main';
import { useResizeObserver } from '@vueuse/core';
import { nextTick } from 'process';
import PreviewWindow from '../preview-window';
import { state as baseState, modalClickMask } from '@/state';
import { evaluateDifficult } from '/src/utils/contants';
import TheTooltip from '/src/components/TheTooltip';

export const getCurrentMonth = () => {
  return [dayjs().startOf('month').valueOf(), dayjs().endOf('month').valueOf()];
};
export default defineComponent({
  name: 'homework-record',
  setup() {
    const state = reactive({
      workVisiable: false,
      resetVisiable: false,
      resetItem: {} as any,
      searchForm: {
        keyword: null as any,
        currentClass: '',
        homeworkType: '',
        currentGradeNum: '',
        subjectId: '',
        gradeYear: '',
        gradeLevel: '',
        homeworkObj: '',
        status: '',
        timer: null as any,
        selfFlag: true
      },
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 6
      },
      gradeNumList: [] as any,
      tableList: [] as any,
      studentVisible: false,
      activeRow: null as any,
      showaddClass: false,
      popSelectYearList: [] as any,
      popSelectLevelList: [] as any,
      previewModal: false,
      previewParams: {
        type: '',
        courseId: '',
        subjectId: '',
        detailId: ''
      } as any
    });
    const formRef = ref();
    const message = useMessage();
    const router = useRouter();
    const route = useRoute();
    const search = () => {
      state.pagination.page = 1;
      getList();
      setCache({ current: state.searchForm, saveKey: route.path });
    };
    state.gradeNumList = getgradeNumList();
    const onReset = () => {
      state.searchForm = {
        keyword: null as any,
        homeworkType: '',
        currentClass: '' as any,
        currentGradeNum: '' as any,
        subjectId: '' as any,
        gradeYear: '' as any,
        gradeLevel: '',
        homeworkObj: '',
        status: '',
        timer: null as any,
        selfFlag: true
      };
      if (state.popSelectYearList.length > 0) {
        state.searchForm.gradeYear = state.popSelectYearList[2].id;
      }
      //
      setCache({ current: state.searchForm, saveKey: route.path });
      state.pagination.page = 1;
      getList();
    };

    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'
          );
        }
      );
    };

    const getList = async () => {
      //   // classGroupList
      state.loading = true;
      try {
        const res = await api_trainingList({
          ...state.searchForm,
          ...state.pagination,
          ...getTimes(
            state.searchForm.timer,
            ['startTime', 'endTime'],
            'YYYY-MM-DD'
          )
        });
        const result = res.data.rows || [];
        result.forEach((item: any) => {
          let pTitle = '';
          let eTitle = '';
          if (
            item.studentLessonTrainingDetails &&
            item.studentLessonTrainingDetails.length > 0
          ) {
            item.studentLessonTrainingDetails.forEach((child: any) => {
              const trainingContent = child.trainingContent
                ? JSON.parse(child.trainingContent)
                : null;
              if (child.trainingType === 'PRACTICE' && child.musicName) {
                pTitle += pTitle
                  ? '《' + child.musicName + '》'
                  : '练习曲目:《' + child.musicName + '》';

                if (trainingContent) {
                  const tempList = [
                    `${trainingContent.practiceChapterBegin}-${trainingContent.practiceChapterEnd}小节`,
                    `速度${trainingContent.practiceSpeed || 0}`,
                    `${trainingContent.trainingTimes}分钟`
                  ];
                  pTitle += tempList.join(' | ') + '；';
                }
              }
              if (child.trainingType === 'EVALUATION' && child.musicName) {
                eTitle += eTitle
                  ? '《' + child.musicName + '》'
                  : '评测曲目:《' + child.musicName + '》';

                if (trainingContent) {
                  const tempList = [
                    `${evaluateDifficult[trainingContent.evaluateDifficult]}`,
                    `${trainingContent.practiceChapterBegin || 0}-${
                      trainingContent.practiceChapterEnd || 0
                    }小节`,
                    `速度${trainingContent.evaluateSpeed || 0}`,
                    `${trainingContent.trainingTimes}分达标`
                  ];
                  eTitle += tempList.join(' | ') + '；';
                }
              }
            });
          }

          item.pTitle = pTitle;
          item.eTitle = eTitle;

          let studentName = item.homeworkObjName;
          if (item.homeworkObjName) {
            const tempObjName = item.homeworkObjName.split(',');
            if (tempObjName.length > 5) {
              studentName =
                tempObjName.slice(0, 5).join('、') +
                `...等${tempObjName.length}${
                  item.homeworkObj === 'CLASS' ? '个班级' : '人'
                }`;
            } else {
              studentName = tempObjName.join('、');
            }
          }
          item.studentName = studentName;
        });
        state.tableList = res.data.rows;
        state.pagination.pageTotal = res.data.total;
        state.loading = false;
      } catch (e) {
        state.loading = false;
        console.log(e);
      }
    };

    // 获取学年
    const getYearList = async () => {
      try {
        const { data } = await getGradeYearList();
        const temp = data || [];
        temp.forEach((i: any) => {
          i.name = i.name + '学年';
        });
        temp.unshift({
          id: '',
          name: '全部学年'
        });
        state.popSelectYearList = temp || [];
        if (temp.length > 0 && !state.searchForm.gradeYear) {
          state.searchForm.gradeYear = temp[2].id;
        }
      } catch {
        //
      }
    };
    // 获取学级
    const getLevelList = async () => {
      try {
        const { data } = await getGradeLevelList();
        const temp = data || [];
        temp.forEach((i: any) => {
          i.name = i.name + '级';
        });
        temp.unshift({
          id: '',
          name: '全部学级'
        });
        state.popSelectLevelList = temp || [];
        if (temp.length > 0 && !state.searchForm.gradeLevel) {
          state.searchForm.gradeLevel = temp[0].id;
        }
      } catch {
        //
      }
    };

    initCache({
      current: state.searchForm,
      callBack: (active: any) => {
        state.searchForm = active;
      }
    });

    const onResetRecord = async () => {
      try {
        await api_withdrawTraining({ lessonTrainingId: state.resetItem.id });
        message.success('撤回成功');
        state.resetVisiable = false;
        search();
      } catch {
        //
      }
    };

    // 预览上课
    // courseId: '' as any, // 课件编号
    //   subjectId: '' as any, // 声部编号
    //   lessonCourseId: '' as any, // 教材编号
    //   lessonCoursewareDetailId: '' as any, // 章节
    //   detailId: '' as any, // 编号 - 课程编号
    //   classGroupId: '' as any, // 上课时需要 班级编号
    const onPreviewAttend = (item: any) => {
      // 判断是否在应用里面
      if (window.matchMedia('(display-mode: standalone)').matches) {
        baseState.application = window.matchMedia(
          '(display-mode: standalone)'
        ).matches;
        state.previewModal = true;
        fscreen();
        state.previewParams = {
          type: 'preview',
          courseId: item.chapterLessonCoursewareId,
          subjectId: null,
          detailId: item.lessonCoursewareKnowledgeDetailId,
          lessonCourseId: item.lessonCoursewareId
        };
      } else {
        const { href } = router.resolve({
          path: '/attend-class',
          query: {
            type: 'preview',
            courseId: item.chapterLessonCoursewareId,
            instrumentId: null,
            detailId: item.lessonCoursewareKnowledgeDetailId,
            lessonCourseId: item.lessonCoursewareId
          }
        });
        window.open(href, +new Date() + '');
      }
    };

    onMounted(async () => {
      state.loading = true;
      await getYearList();
      await getLevelList();
      await getList();
      state.loading = false;
    });
    return () => (
      <div class={styles.listWrap}>
        <div class={styles.searchList}>
          <NForm label-placement="left" inline ref={formRef}>
            <NFormItem>
              <SearchInput
                {...{ placeholder: '请输入作业标题关键词' }}
                class={styles.searchInput}
                searchWord={state.searchForm.keyword}
                onChangeValue={(val: string) =>
                  (state.searchForm.keyword = val)
                }></SearchInput>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: [
                    { id: '', name: '全部类型' },
                    { id: 'CLASSWORK', name: '课外作业' },
                    { id: 'HOMEWORK', name: '课后作业' }
                  ],
                  placeholder: '选择类型',
                  clearable: true,
                  inline: true,
                  labelField: 'name',
                  valueField: 'id'
                } as any)}
                v-model:value={state.searchForm.homeworkType}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: [
                    { id: '', name: '作业对象' },
                    { id: 'PERSON', name: '个人' },
                    { id: 'CLASS', name: '班级' }
                  ],
                  placeholder: '选择作业对象',
                  clearable: true,
                  inline: true,
                  labelField: 'name',
                  valueField: 'id'
                } as any)}
                v-model:value={state.searchForm.homeworkObj}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: state.popSelectYearList,
                  placeholder: '选择学年',
                  clearable: true,
                  inline: true,
                  labelField: 'name',
                  valueField: 'id'
                } as any)}
                v-model:value={state.searchForm.gradeYear}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: state.popSelectLevelList,
                  placeholder: '选择学级',
                  clearable: true,
                  inline: true,
                  labelField: 'name',
                  valueField: 'id'
                } as any)}
                v-model:value={state.searchForm.gradeLevel}></CSelect>
            </NFormItem>

            <NFormItem>
              <CSelect
                {...({
                  options: state.gradeNumList,
                  placeholder: '选择年级',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.currentGradeNum}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: classArray,
                  placeholder: '选择班级',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.currentClass}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: [
                    { value: '', label: '全部状态' },
                    { value: 0, label: '进行中' },
                    { value: 1, label: '已结束' }
                  ],
                  placeholder: '选择状态',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.status}></CSelect>
            </NFormItem>
            <NFormItem>
              <CDatePicker
                class={styles.CDatePickerItem}
                separator={'-'}
                type="daterange"
                startPlaceholder="布置开始时间"
                endPlaceholder="布置结束时间"
                v-model:value={state.searchForm.timer}
                timerValue={state.searchForm.timer}></CDatePicker>
            </NFormItem>
            <NFormItem>
              <NSpace justify="end">
                <NButton type="primary" class="searchBtn" onClick={search}>
                  搜索
                </NButton>
                <NButton
                  type="primary"
                  ghost
                  class="resetBtn"
                  onClick={onReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </div>
        <NButton
          class={styles.addBtn}
          type="primary"
          onClick={() => {
            state.workVisiable = true;
            nextTick(() => {
              getModalHeight();
            });
          }}
          v-slots={{
            icon: () => (
              <NImage
                class={styles.addBtnIcon}
                previewDisabled
                src={add}></NImage>
            )
          }}>
          布置作业
        </NButton>
        <div class={styles.tableWrap}>
          <NSpin show={state.loading}>
            <div style={{ minHeight: '40vh' }}>
              <div class={styles.listSection}>
                {state.tableList.map((item: any) => (
                  <div
                    class={styles.item}
                    onClick={() => {
                      router.push({
                        path: '/homework-record-detail',
                        query: {
                          id: item.id,
                          name: item.name
                        }
                      });
                    }}>
                    <div class={styles.header}>
                      <NAvatar
                        class={styles.navatar}
                        round
                        src={item.teacherAvatar || teacherIcon}
                      />
                      <div class={styles.userInfo}>
                        <h2>{item.teacherName}</h2>
                        <p>
                          布置时间：
                          {dayjs(item.createTime).format('YYYY-MM-DD HH:mm')}
                          <span> | </span>
                          <span>
                            截止时间：
                            {dayjs(item.expireDate).format('YYYY-MM-DD')}
                          </span>
                        </p>
                      </div>
                      <div class={item.status ? styles.over : styles.ing}>
                        {/* {item.status ? '已结束' : '进行中'} */}
                      </div>
                    </div>
                    <div class={styles.content}>
                      {/* <div> */}
                      <div class={styles.homeTitle}>
                        <p>
                          <span class={styles[item.homeworkType]}>
                            {item.homeworkType === 'CLASSWORK'
                              ? '课外'
                              : '课后'}
                          </span>
                          {item.name}
                        </p>

                        <NSpace>
                          {item.chapterLessonCoursewareId && (
                            <NButton
                              class={styles.errorBtn}
                              text
                              color="#1677FF"
                              onClick={(e: any) => {
                                e.stopPropagation();
                                // state.resetVisiable = true;
                                // state.resetItem = item;
                                onPreviewAttend(item);
                              }}>
                              查看课件
                            </NButton>
                          )}

                          {!item.status && (
                            <NButton
                              class={styles.errorBtn}
                              text
                              color="#1677FF"
                              onClick={(e: any) => {
                                e.stopPropagation();
                                state.resetVisiable = true;
                                state.resetItem = item;
                              }}>
                              撤回
                            </NButton>
                          )}
                        </NSpace>
                      </div>
                      <div class={styles.homeContent}>
                        <span class={styles.title}>作业对象：</span>
                        <span class={styles.text}>{item.studentName}</span>
                      </div>
                      <div class={[styles.homeContent, styles.homeworkText]}>
                        <span class={styles.title}>作业内容：</span>
                        <div class={styles.pSection}>
                          {item.pTitle && (
                            <NTooltip
                              trigger="hover"
                              class={styles.theTooltip}
                              delay={500}>
                              {{
                                trigger: () => (
                                  <p
                                    class={[
                                      styles.text,
                                      styles.p1,
                                      styles.theTooltip
                                    ]}>
                                    {item.pTitle}
                                  </p>
                                ),
                                default: () => item.pTitle
                              }}
                            </NTooltip>
                          )}
                          {item.eTitle && (
                            // <p class={[styles.text, styles.p2]}>
                            //   <TheTooltip
                            //     maxWidth={500}
                            //     content={item.eTitle}
                            //     style={{ maxWidth: '100% !important' }}
                            //   />
                            // </p>
                            <NTooltip
                              trigger="hover"
                              class={styles.theTooltip}
                              delay={500}>
                              {{
                                trigger: () => (
                                  <p
                                    class={[
                                      styles.text,
                                      styles.p2,
                                      styles.theTooltip
                                    ]}>
                                    {item.eTitle}
                                  </p>
                                ),
                                default: () => item.eTitle
                              }}
                            </NTooltip>
                          )}
                        </div>
                      </div>
                      <div class={styles.homeSubmit}>
                        <span class={styles.title}>已提交：</span>
                        <span class={styles.text}>
                          {item.trainingNum || 0}/{item.expectNum || 0}人
                        </span>
                        <NDivider vertical />
                        <span class={styles.title}>提交率：</span>
                        <span class={styles.text}>
                          {item.trainingRate || 0}%
                        </span>
                        <NDivider vertical />
                        <span class={styles.title}>达标人数：</span>
                        <span class={styles.text}>
                          {item.standardNum || 0}人
                        </span>
                        <NDivider vertical />
                        <span class={styles.title}>达标率：</span>
                        <span class={styles.text}>
                          {item.qualifiedRate || 0}%
                        </span>
                      </div>
                      {/* </div> */}
                    </div>
                  </div>
                ))}
              </div>
              {state.tableList.length <= 0 && !state.loading && (
                <TheEmpty class={styles.nowEmpty} />
              )}
            </div>
          </NSpin>

          {state.tableList.length > 0 && (
            <Pagination
              v-model:page={state.pagination.page}
              v-model:pageSize={state.pagination.rows}
              v-model:pageTotal={state.pagination.pageTotal}
              onList={getList}
              // sync
            />
          )}
        </div>
        <NModal
          maskClosable={modalClickMask}
          v-model:show={state.resetVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'撤回作业'}>
          <div class={styles.studentRemove}>
            <p>
              撤回作业后，此条作业将被删除，是否确认撤回【{state.resetItem.name}
              】？
            </p>

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

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

        {/* 应用内预览或上课 */}
        <PreviewWindow
          v-model:show={state.previewModal}
          type="attend"
          params={state.previewParams}
        />
      </div>
    );
  }
});
