import { defineComponent, onMounted, reactive } from 'vue';
import { NAvatar, NButton, NForm, NFormItem, NSpace, NTag } from 'naive-ui';
import Pagination from '@/components/pagination';
import { courseSchedulePage } from '../api';
import { useRoute } from 'vue-router';
import CDatePicker from '/src/components/CDatePicker';
import styles from './classRecord.module.less';
import teacherIcon from '@components/layout/images/teacherIcon.png';
import dayjs from 'dayjs';
import { getTimes } from '/src/utils';
import TheEmpty from '/src/components/TheEmpty';
import CSelect from '/src/components/CSelect';
import { api_teacherPage } from '../../setting/api';
import { useUserStore } from '/src/store/modules/users';
import { initCache, setCache } from '/src/hooks/use-async';
export default defineComponent({
  name: 'class-record',
  setup() {
    const user = useUserStore();
    const route = useRoute();

    const formatDefaultTime = () => {
      const gradeYear: any = route.query.gradeYear;
      if (gradeYear) {
        const yearStr = `${gradeYear}-9-1`;
        const yearStrEnd = `${Number(gradeYear) + 1}-8-31`;
        return [dayjs(yearStr).valueOf(), dayjs(yearStrEnd).valueOf()];
      } else {
        const nowTime = dayjs().format('YYYY-MM-DD');
        return [
          dayjs(nowTime).subtract(1, 'month').valueOf(),
          dayjs(nowTime).valueOf()
        ];
      }
    };

    const state = reactive({
      searchForm: {
        teacherId: '',
        createTimer: formatDefaultTime() as any
      },
      teacherList: [],
      loading: false,
      pagination: {
        page: 1,
        rows: 12,
        pageTotal: 0
      },
      tableList: [] as any
    });
    const search = () => {
      state.pagination.page = 1;
      getList();
      setCache({
        current: state.searchForm,
        saveKey: 'classDetailRecord'
      });
    };

    const onReset = () => {
      state.searchForm = {
        teacherId: '',
        createTimer: formatDefaultTime() as any
      };
      search();
      setCache({
        current: state.searchForm,
        saveKey: 'classDetailRecord'
      });
    };

    initCache({
      current: state.searchForm,
      saveKey: 'classDetailRecord',
      callBack: (active: any) => {
        state.searchForm = active;
      }
    });
    const getList = async () => {
      state.loading = true;
      try {
        const { data } = await courseSchedulePage({
          classGroupId: route.query.id,
          teacherId: state.searchForm.teacherId,
          ...getTimes(
            state.searchForm.createTimer,
            ['startTime', 'endTime'],
            'YYYY-MM-DD'
          ),
          ...state.pagination
        });
        const rows = data.rows || [];
        rows.forEach((row: any) => {
          row.lessonCourseware = row.lessonCoursewareJson
            ? JSON.parse(row.lessonCoursewareJson)
            : {};
        });
        state.tableList = rows;
        state.pagination.pageTotal = data.total;
        state.loading = false;
      } catch (e) {
        state.loading = false;
      }
    };

    const getTeachers = async () => {
      try {
        const { data } = await api_teacherPage({
          schoolId: user.info.schoolInfos?.[0]?.id,
          page: 1,
          rows: 1000
        });
        const tempList = data.rows || [];
        const tempT = [] as any;
        tempList.forEach((item: any) => {
          tempT.push({
            label: item.nickname,
            value: item.id
          });
        });
        state.teacherList = tempT;
      } catch {
        //
      }
    };
    onMounted(() => {
      getTeachers();
      getList();
    });
    return () => (
      <div>
        <div class={styles.searchList}>
          <NForm label-placement="left" inline>
            <NFormItem>
              <CSelect
                {...({
                  options: [
                    {
                      label: '全部老师',
                      value: ''
                    },
                    ...state.teacherList
                  ],
                  placeholder: '全部老师',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.teacherId}></CSelect>
            </NFormItem>

            <NFormItem>
              <CDatePicker
                v-model:value={state.searchForm.createTimer}
                timerValue={state.searchForm.createTimer}
                separator={'至'}
                type="daterange"></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>
        <div class={styles.tableWrap}>
          <NSpace class={styles.tableSpace}>
            {state.tableList.map((item: any) => (
              <div class={styles.tableContainer}>
                <div class={styles.header}>
                  <div class={styles.time}>
                    {dayjs(item.startTime).format('YYYY-MM-DD HH:mm')}
                  </div>
                  {route.query.name && (
                    <NTag type="primary" class={styles.ntag} strong>
                      {route.query.name}
                    </NTag>
                  )}
                </div>
                <div class={styles.content}>
                  <NAvatar
                    class={styles.navatar}
                    round
                    src={item.teacherAvatar || teacherIcon}
                  />
                  <div class={styles.userInfo}>
                    <h2>{item.teacherName}</h2>
                    <p>
                      {item.subjectName && (
                        <span class={styles.subjectName}>
                          {item.subjectName}
                        </span>
                      )}
                      {item.lessonCourseware.lessonCoursewareName} |{' '}
                      {item.lessonCourseware.lessonCoursewareDetailName}|{' '}
                      {
                        item.lessonCourseware
                          .lessonCoursewareKnowledgeDetailName
                      }
                      | {item.useChapterLessonCoursewareName}
                    </p>
                  </div>
                </div>
              </div>
            ))}
          </NSpace>
          {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}
              pageSizes={[12, 24, 36, 48]}
              sync
              saveKey="classRecord-key"
            />
          )}

          {state.tableList.length <= 0 && <TheEmpty class={styles.nowEmpty} />}
        </div>
      </div>
    );
  }
});
