import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NModal,
  NSpace
} from 'naive-ui';
import CSelect from '@/components/CSelect';
import Pagination from '@/components/pagination';
import { getStudentAfterWork } from '../api';
import { useRoute } from 'vue-router';
import CDatePicker from '/src/components/CDatePicker';
import {
  getNowDateAndMonday,
  getNowDateAndSunday,
  getTimes
} from '/src/utils/dateFormat';
import { trainingStatusArray } from '@/utils/searchArray';
import StudentTraomomhDetails from '../modals/studentTraomomhDetails';
import dayjs from 'dayjs';
import TheEmpty from '/src/components/TheEmpty';
import { initCache, setCache } from '/src/hooks/use-async';
import { modalClickMask } from '/src/state';
export default defineComponent({
  name: 'student-studentList',
  setup() {
    const state = reactive({
      searchForm: { keyword: '', trainingStatus: '' as any },
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 4
      },
      tableList: [] as any,
      workInfo: {
        createTime: '',
        expireDate: '',
        teacherAvatar: '',
        teacherName: ''
      },
      detailVisiable: false,
      activeRow: null as any,
      index: 0
    });
    const timer = ref<[number, number]>([
      // new Date('2023-01-01').getTime(),
      getNowDateAndMonday(new Date().getTime()),
      getNowDateAndSunday(new Date().getTime())
    ]);
    const TrainingDetailsRef = ref();
    const route = useRoute();
    // const routerList = ref([
    //   { name: '班级管理', path: '/classList' },
    //   { name: route.query.name, path: '/classDetail' },
    //   { name: route.query.teacherName, path: '/afterWorkDetail' }
    // ] as any);

    const search = () => {
      state.pagination.page = 1;
      getList();
      setCache({
        current: { ...state.searchForm, timer: timer.value },
        saveKey: 'studentDetailAfterWork'
      });
    };

    const onReset = () => {
      state.searchForm = { keyword: '', trainingStatus: '' as any };
      timer.value = [
        getNowDateAndMonday(new Date().getTime()),
        getNowDateAndSunday(new Date().getTime())
      ];
      search();
      setCache({
        current: { ...state.searchForm, timer: timer.value },
        saveKey: 'studentDetailAfterWork'
      });
    };

    initCache({
      current: { ...state.searchForm, timer: timer.value },
      saveKey: 'studentDetailAfterWork',
      callBack: (active: any) => {
        state.searchForm = active;
        timer.value = active.timer;
      }
    });
    const getList = async () => {
      state.loading = true;
      try {
        const res = await getStudentAfterWork({
          studentId: route.query.studentId,
          ...state.searchForm,
          ...state.pagination,
          ...getTimes(timer.value, ['startTime', 'endTime'], 'YYYY-MM-DD')
        });

        state.tableList = res.data.rows;

        state.pagination.pageTotal = res.data.total;
        state.loading = false;
      } catch (e) {
        state.loading = false;
        console.log(e);
      }
    };
    // const getWorkInfo = async () => {
    //   console.log(route.query);
    //   try {
    //     const res = await getWorkDetail({ trainingId: route.query.trainingId });
    //     state.workInfo = { ...res.data };
    //   } catch (e) {
    //     console.log(e);
    //   }
    // };

    const lookDetail = (row: any, index: number) => {
      console.log(index, 'index');
      state.index = index + 1;
      state.activeRow = row;
      state.detailVisiable = true;
    };
    onMounted(() => {
      // getWorkInfo();
      getList();
    });
    const columns = () => {
      return [
        {
          title: '布置老师',
          key: 'teacherName'
        },
        {
          title: '布置时间',
          key: 'createTime',
          render(row: any) {
            return row.createTime
              ? dayjs(row.createTime).format('YYYY-MM-DD HH:mm')
              : '--';
          }
        },
        {
          title: '截止时间',
          key: 'expireDate',
          render(row: any) {
            return row.expireDate
              ? dayjs(row.expireDate).format('YYYY-MM-DD')
              : '--';
          }
        },
        {
          title: '最后提交时间',
          key: 'submitTime',
          render(row: any) {
            return row.submitTime
              ? dayjs(row.submitTime).format('YYYY-MM-DD')
              : '--';
          }
        },
        {
          title: '提交状态',
          key: 'sex',
          render(row: any) {
            return (
              <div>
                {row.trainingStatus == 'UNSUBMITTED' ? (
                  <p class={styles.nosub} style={{ color: '#aaa' }}>
                    未提交
                  </p>
                ) : null}
                {row.trainingStatus == 'SUBMITTED' ? (
                  <p style={{ color: '#EA4132' }} class={styles.ison}>
                    未达标
                  </p>
                ) : null}
                {row.trainingStatus == 'TARGET' ? (
                  <p class={styles.isok}>达标</p>
                ) : null}
              </div>
            );
          }
        },
        {
          title: '操作',
          key: 'id',
          render(row: any, index: number) {
            return (
              <NButton
                text
                type="primary"
                onClick={() => {
                  lookDetail(row, index);
                }}>
                详情
              </NButton>
            );
          }
        }
      ];
    };

    // const goToNext = () => {
    //   ++state.index;

    //   state.activeRow = state.tableList[state.index - 1];

    //   TrainingDetailsRef.value.getTrainingDetail(
    //     state.activeRow.studentLessonTrainingId
    //   );
    // };
    // const gotoPre = () => {
    //   --state.index;
    //   state.activeRow = state.tableList[state.index - 1];
    //   TrainingDetailsRef.value.getTrainingDetail(
    //     state.activeRow.studentLessonTrainingId
    //   );
    // };
    return () => (
      <div>
        <div>
          <div class={styles.searchList}>
            <NForm label-placement="left" inline>
              <NFormItem>
                <CDatePicker
                  v-model:value={timer.value}
                  separator={'至'}
                  type="daterange"
                  timerValue={timer.value}></CDatePicker>
              </NFormItem>
              <NFormItem>
                <CSelect
                  {...({
                    options: [
                      {
                        label: '全部状态',
                        value: ''
                      },
                      ...trainingStatusArray
                    ],
                    placeholder: '提交状态',
                    clearable: true,
                    inline: true
                  } as any)}
                  v-model:value={state.searchForm.trainingStatus}></CSelect>
              </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>
            <NDataTable
              v-slots={{
                empty: () => <TheEmpty></TheEmpty>
              }}
              class={styles.classTable}
              loading={state.loading}
              columns={columns()}
              data={state.tableList}></NDataTable>
            <Pagination
              v-model:page={state.pagination.page}
              v-model:pageSize={state.pagination.rows}
              v-model:pageTotal={state.pagination.pageTotal}
              onList={getList}
              sync
            />
          </div>
        </div>
        <NModal
          maskClosable={modalClickMask}
          v-model:show={state.detailVisiable}
          preset="card"
          class={['modalTitle background', styles.wordDetailModel]}
          title={'作业详情'}>
          <StudentTraomomhDetails
            // onNext={() => goToNext()}
            // onPre={() => gotoPre()}
            ref={TrainingDetailsRef}
            onClose={() => (state.detailVisiable = false)}
            total={state.tableList.length}
            current={state.index}
            activeRow={state.activeRow}></StudentTraomomhDetails>
        </NModal>
      </div>
    );
  }
});
