import { defineComponent, reactive, onMounted, ref } from 'vue';
import styles from './index.module.less';
import {
  NAvatar,
  NButton,
  NDivider,
  NForm,
  NFormItem,
  NImage,
  NModal,
  NSpace,
  NSpin,
  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 { 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';

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: '',
        currentGradeNum: '',
        subjectId: '',
        gradeYear: '',
        gradeLevel: '',
        homeworkObj: '',
        status: '',
        timer: getCurrentMonth() 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
    });
    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,
        currentClass: '' as any,
        currentGradeNum: '' as any,
        subjectId: '' as any,
        gradeYear: '' as any,
        gradeLevel: '',
        homeworkObj: '',
        status: '',
        timer: getCurrentMonth() as any,
        selfFlag: true
      };
      if (state.popSelectYearList.length > 0) {
        state.searchForm.gradeYear = state.popSelectYearList[1].id;
      }
      // getList();
      setCache({ current: state.searchForm, saveKey: route.path });
    };

    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) => {
              if (child.trainingType === 'PRACTICE' && child.musicName) {
                pTitle += pTitle ? '、' + child.musicName : child.musicName;
              }
              if (child.trainingType === 'EVALUATION' && child.musicName) {
                eTitle += eTitle ? '、' + child.musicName : child.musicName;
              }
            });
          }
          item.pTitle = pTitle;
          item.eTitle = eTitle;
        });
        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[1].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 {
        //
      }
    };

    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: '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"
                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 class={styles.listSection}>
              {state.tableList.map((item: any) => (
                <div class={styles.item}>
                  <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')}
                        <span>|</span>
                        <span>
                          截止时间：
                          {dayjs(item.expireDate).format('YYYY-MM-DD')}
                        </span>
                      </p>
                    </div>
                    <div class={item.status === 1 ? styles.over : styles.ing}>
                      {item.status === 1 ? '已结束' : '进行中'}
                    </div>
                  </div>
                  <div class={styles.content}>
                    <div>
                      <div class={styles.homeTitle}>{item.name}</div>
                      <div class={styles.homeContent}>
                        <span class={styles.title}>作业对象：</span>
                        <span class={styles.text}>{item.homeworkObjName}</span>
                      </div>
                      <div class={[styles.homeContent, styles.homeworkText]}>
                        <span class={styles.title}>作业内容：</span>
                        <div class={styles.pSection}>
                          {item.pTitle && (
                            <p class={[styles.text, styles.p1]}>
                              {item.pTitle}
                            </p>
                          )}
                          {item.eTitle && (
                            <p class={[styles.text, styles.p2]}>
                              {item.eTitle}
                            </p>
                          )}
                        </div>
                      </div>
                      <div class={styles.homeSubmit}>
                        <span class={styles.title}>已提交：</span>
                        <span class={styles.text}>
                          {item.trainingNum || 0}/{item.trainingNum || 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>

                    <NButton
                      class={styles.errorBtn}
                      type="error"
                      color="#F94D50"
                      onClick={() => {
                        state.resetVisiable = true;
                        state.resetItem = item;
                      }}>
                      撤回
                    </NButton>
                  </div>
                </div>
              ))}
            </div>
            {state.tableList.length <= 0 && (
              <TheEmpty class={styles.nowEmpty} />
            )}
          </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
          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
          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日') + '-课后作业'
                }}
              />
            </div>
            <div class={styles.resourceMain}>
              <ResourceMain cardType="homerowk-record" />
            </div>
          </div>
        </NModal>
      </div>
    );
  }
});
