import { defineComponent, onMounted, reactive, ref, watch } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NImage,
  NModal,
  NSelect,
  NSpace
} from 'naive-ui';
import CSelect from '@/components/CSelect';
import Pagination from '@/components/pagination';
import { classGroupDetail, getTrainingList } from '../api';
import add from './images/add.png';
import { useRoute, useRouter } from 'vue-router';
import CDatePicker from '/src/components/CDatePicker';
import ClassTrainingDetails from '../modals/classTrainingDetails';
import {
  getNowDateAndMonday,
  getNowDateAndSunday,
  getTimes
} from '@/utils/dateFormat';
import TrainSettings from '../../attend-class/model/train-settings';
import TheEmpty from '/src/components/TheEmpty';
import { initCache, setCache } from '/src/hooks/use-async';
import StudentTraomomhDetails from '../../studentList/modals/studentTraomomhDetails';
import { modalClickMask } from '/src/state';
import dayjs from 'dayjs';
export default defineComponent({
  name: 'afterWork',
  props: {
    upgradeFlag: {
      type: Number
    }
  },
  setup(props) {
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      upgradeFlag: props.upgradeFlag == 0 ? true : false, // 是否为历史班
      searchForm: {
        status: '' as any,
        timer: [
          getNowDateAndMonday(new Date().getTime()),
          getNowDateAndSunday(new Date().getTime())
        ] as any
      },
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 4
      },
      tableList: [] as any,
      addWorkVisible: false,
      activeRow: null as any,
      detailVisiable: false
    });

    watch(
      () => props.upgradeFlag,
      () => {
        state.upgradeFlag = props.upgradeFlag == 0 ? true : false;
      }
    );

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

    const onReset = () => {
      state.searchForm = {
        status: '' as any,
        timer: [
          getNowDateAndMonday(new Date().getTime()),
          getNowDateAndSunday(new Date().getTime())
        ]
      };
      search();
      setCache({ current: state.searchForm, saveKey: 'classDetailAfterWork' });
    };
    initCache({
      current: state.searchForm,
      saveKey: 'classDetailAfterWork',
      callBack: (active: any) => {
        state.searchForm = active;
      }
    });

    const getList = async () => {
      state.loading = true;

      try {
        const { timer, ...more } = state.searchForm;
        const res = await getTrainingList({
          classGroupId: route.query.id,
          ...more,
          ...state.pagination,
          ...getTimes(timer, ['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);
      }
    };
    onMounted(() => {
      getList();
    });

    const columns = () => {
      return [
        {
          title: '布置老师',
          key: 'teacherName'
        },
        {
          title: '布置时间',
          key: 'createTime',
          render(row: any) {
            return <>{row.createTime}</>;
          }
        },
        {
          title: '截止时间',
          key: 'expireDate',
          render(row: any) {
            return row.expireDate
              ? dayjs(row.expireDate).format('YYYY-MM-DD')
              : '--';
          }
        },
        {
          title: '作业状态',
          key: 'status',
          render(row: any) {
            return !row.status ? (
              <div class={styles.indDot}>
                <span></span> 进行中
              </div>
            ) : (
              <div class={styles.endDot}>
                <span></span>已结束
              </div>
            );
          }
        },
        {
          title: '布置人数',
          key: 'expectNum'
        },
        {
          title: '提交人数',
          key: 'trainingNum'
        },
        {
          title: '达标人数',
          key: 'standardNum'
        },
        {
          title: '提交率',
          key: 'trainingRate',
          render(row: any) {
            return <>{row.trainingRate}%</>;
          }
        },
        {
          title: '达标率',
          key: 'qualifiedRate',
          render(row: any) {
            return <>{row.qualifiedRate}%</>;
          }
        },
        // {
        //   title: '',
        //   key: 'sex',
        //   render(row: any) {
        //     return <>{row.sex == '0' ? '女' : '男'}</>;
        //   }
        // },
        {
          title: '操作',
          key: 'id',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  text
                  type="primary"
                  onClick={() => gotoWorkDetail(row)}>
                  详情
                </NButton>
                {/* <NButton
                  text
                  type="primary"
                  onClick={() => lookWorkDetail(row)}>
                  作业详情
                </NButton> */}
              </NSpace>
            );
          }
        }
      ];
    };
    const gotoWorkDetail = (row: any) => {
      router.push({
        path: '/afterWorkDetail',
        query: {
          ...route.query,
          classGroupId: route.query.id,
          teacherName: row.teacherName,
          trainingId: row.id
        }
      });
    };

    const lookWorkDetail = (row: any) => {
      state.activeRow = row;
      state.detailVisiable = true;
    };
    return () => (
      <div>
        <div class={styles.searchList}>
          <NForm label-placement="left" inline>
            <NFormItem>
              <CDatePicker
                v-model:value={state.searchForm.timer}
                separator={'至'}
                type="daterange"
                timerValue={state.searchForm.timer}></CDatePicker>
            </NFormItem>

            <NFormItem>
              <CSelect
                {...({
                  options: [
                    {
                      label: '全部状态',
                      value: ''
                    },
                    {
                      label: '已结束',
                      value: 1
                    },
                    {
                      label: '进行中',
                      value: 0
                    }
                  ],
                  placeholder: '作业状态',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.status}></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>
        {/* {!state.upgradeFlag && (
          <NButton
            class={styles.addBtn}
            type="primary"
            onClick={() => (state.addWorkVisible = true)}>
            布置作业
          </NButton>
        )} */}

        <div class={styles.tableWrap}>
          <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>
        <NModal
          maskClosable={modalClickMask}
          v-model:show={state.addWorkVisible}
          preset="card"
          class={[styles.attendClassModal, styles.trainClassModal]}
          title={'作业设置'}>
          <TrainSettings
            classGroupId={route.query.id as string}
            onClose={() => {
              getList();
              state.addWorkVisible = false;
            }}
          />
        </NModal>
        <NModal
          maskClosable={modalClickMask}
          v-model:show={state.detailVisiable}
          preset="card"
          class={['modalTitle background', styles.wordDetailModel]}
          title={'作业详情'}>
          <ClassTrainingDetails
            onClose={() => (state.detailVisiable = false)}
            activeRow={state.activeRow}></ClassTrainingDetails>
        </NModal>
      </div>
    );
  }
});
