import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import {
  Button,
  Cell,
  CellGroup,
  DropdownItem,
  DropdownMenu,
  Grid,
  GridItem,
  Icon,
  List
} from 'vant';
import iconTimer from '@/common/images/icon-timer.png';
import SkeletionIndexModal from './skeletion-index.modal';
import { useRouter } from 'vue-router';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';
import MFullRefresh from '@/components/m-full-refresh';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'patrol-evaluation',
  setup() {
    const router = useRouter();
    const forms = reactive({
      isClick: false,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: true,
        finished: false,
        refreshing: false
      },
      params: {
        startTime: '',
        endTime: '',
        page: 1,
        rows: 20
      },
      statusValue: 'week',
      statusColumns: [
        { text: '本周', value: 'week' },
        { text: '本月', value: 'month' },
        { text: '本学期', value: 'term' }
      ],
      list: []
    });

    const getList = async () => {
      try {
        if (forms.isClick) return;
        forms.isClick = true;
        const { data } = await request.post(
          '/api-web/coursePatrolEvaluation/pageStat',
          {
            data: forms.params
          }
        );
        const result = data || {};

        // 判断是否有数据
        if (forms.listState.refreshing) {
          forms.list = result.rows || [];
        } else {
          forms.list = forms.list.concat(result.rows || []);
        }

        forms.listState.finished = result.pageNo >= result.totalPage;
        forms.params.page = result.pageNo + 1;
      } catch {
        forms.listState.finished = true;
      } finally {
        setTimeout(() => {
          forms.listState.dataShow = forms.list.length > 0;
          forms.listState.refreshing = false;
          forms.listState.loading = false;
          forms.isClick = false;
        }, 500);
      }
    };

    const onRefresh = () => {
      forms.params.page = 1;
      getList();
    };

    const formatTimer = () => {
      if (forms.statusValue == 'week') {
        const startDay = dayjs()
          .startOf('week')
          .add(1, 'day')
          .format('YYYY-MM-DD');
        const endDay = dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD');
        forms.params.startTime = startDay;
        forms.params.endTime = endDay;
      } else if (forms.statusValue == 'month') {
        const startDay = dayjs().startOf('month').format('YYYY-MM-DD');
        const endDay = dayjs().endOf('month').format('YYYY-MM-DD');
        forms.params.startTime = startDay;
        forms.params.endTime = endDay;
      } else if (forms.statusValue == 'term') {
        const year = dayjs().year();
        const startTime = '09-01';
        const endTime = '03-01';
        const sysStartTime = dayjs(year + startTime).format('YYYY-MM-DD');
        const sysEndTime = dayjs(year + endTime).format('YYYY-MM-DD');
        const nowTime = dayjs().format('YYYY-MM-DD');
        const before = dayjs(nowTime).isBefore(dayjs(sysStartTime));
        const after = dayjs(nowTime).isBefore(dayjs(sysEndTime));

        console.log(before, after, 'before');
        if (before && after) {
          forms.params.startTime = dayjs(year - 1 + startTime).format(
            'YYYY-MM-DD'
          );
          forms.params.endTime = dayjs(dayjs().year() + endTime)
            .subtract(1, 'day')
            .format('YYYY-MM-DD');
        }

        if (!before && !after) {
          forms.params.startTime = dayjs(dayjs().year() + startTime).format(
            'YYYY-MM-DD'
          );
          forms.params.endTime = dayjs(dayjs().year() + endTime)
            .add(1, 'year')
            .subtract(1, 'day')
            .format('YYYY-MM-DD');
          // 下一年的上学期
        }

        if (before && !after) {
          forms.params.startTime = dayjs(year + endTime).format('YYYY-MM-DD');
          forms.params.endTime = dayjs(year + startTime)
            .subtract(1, 'day')
            .format('YYYY-MM-DD');
        }
      }
    };

    onMounted(() => {
      formatTimer();
      getList();
    });
    return () => (
      <div class={styles['patrol-evaluation']}>
        <MSticky position="top">
          <MHeader />

          <DropdownMenu class={styles.patrolDropDown}>
            <DropdownItem
              v-model={forms.statusValue}
              options={forms.statusColumns as any}
              onChange={() => {
                formatTimer();
                forms.listState.dataShow = true;
                forms.listState.refreshing = true;
                forms.params.page = 1;
                getList();
              }}></DropdownItem>
          </DropdownMenu>
        </MSticky>

        <SkeletionIndexModal v-model:show={forms.listState.loading}>
          <MFullRefresh
            v-model:modelValue={forms.listState.refreshing}
            onRefresh={() => onRefresh()}
            style={{
              minHeight: `calc(100vh - var(--header-height))`
            }}>
            <List
              finished={forms.listState.finished}
              finishedText=" "
              style={{ overflow: 'hidden' }}
              onLoad={getList}
              immediateCheck={false}>
              {forms.listState.dataShow ? (
                forms.list.map((item: any) => (
                  <CellGroup inset class={styles.cellGroup}>
                    <Cell center>
                      {{
                        title: () => (
                          <div class={styles.timer}>
                            <Icon name={iconTimer} class={styles.iconTimer} />
                            {item.date}
                          </div>
                        ),
                        label: () => (
                          <div class={styles.patrolContainer}>
                            <Grid columnNum={2} border={false}>
                              <GridItem>
                                {{
                                  icon: () => (
                                    <div class={styles.num}>
                                      <span>{item.patrolCount}</span>节
                                    </div>
                                  ),
                                  text: () => (
                                    <div class="van-grid-item__text">
                                      已评价
                                    </div>
                                  )
                                }}
                              </GridItem>
                              <GridItem>
                                {{
                                  icon: () => (
                                    <div class={styles.num}>
                                      <span>{item.totalCount}</span>节
                                    </div>
                                  ),
                                  text: () => (
                                    <div class="van-grid-item__text">
                                      全部课程
                                    </div>
                                  )
                                }}
                              </GridItem>
                            </Grid>
                            <Button
                              type="primary"
                              class={styles.btn}
                              size="small"
                              round
                              onClick={() => {
                                router.push({
                                  path: '/patrol-evaluation-detail',
                                  query: {
                                    date: item.date
                                  }
                                });
                              }}>
                              查看详情
                            </Button>
                          </div>
                        )
                      }}
                    </Cell>
                  </CellGroup>
                ))
              ) : (
                <MEmpty
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`
                  }}
                  description="暂无数据"
                />
              )}
            </List>
          </MFullRefresh>
        </SkeletionIndexModal>
      </div>
    );
  }
});
