import OSticky from '@/components/o-sticky'
import {
  ActionSheet,
  Button,
  closeToast,
  DatePicker,
  Grid,
  GridItem,
  Icon,
  Image,
  List,
  Picker,
  Popover,
  Popup,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
  showToast
} from 'vant'
import { computed, defineComponent, nextTick, onMounted, reactive, Teleport } from 'vue'
import styles from './information.module.less'
import iconSaveImage from '../images/icon-save-image.png'
import iconWechat from '../images/icon-wechat.png'
import OQrcode from '@/components/o-qrcode'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import { CountUp } from 'countup.js'
import OEmpty from '@/components/o-empty'
import dayjs from 'dayjs'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
dayjs.extend(isSameOrBefore, isSameOrAfter)
import { promisefiyPostMessage, postMessage } from '@/helpers/native-message'
import html2canvas from 'html2canvas'
import OActionSheet from '@/components/o-action-sheet'
import { formatterDatePicker } from '@/helpers/utils'

export default defineComponent({
  name: 'detail-information',
  props: {
    termTimes: {
      type: Object,
      default: {}
    }
  },
  setup(props) {
    const startTime = computed(() => props.termTimes.start)
    const endTime = computed(() => props.termTimes.end)
    const route = useRoute()
    const router = useRouter()

    const state = reactive({
      timeShow: false,
      currentData: [dayjs().year() + ''],
      actionText: '上学期',
      actionType: 'up',
      actionTerm: [
        { name: '上学期', selected: true, value: 'up' },
        { name: '下学期', value: 'down' }
      ],
      oPopover: false,
      check: [],
      checkboxRefs: [] as any,
      isLoading: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      bottomHeight: 0,
      params: {
        startTime: dayjs(dayjs().year() + startTime.value).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(dayjs().year() + endTime.value)
          .add(1, 'year')
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss'),
        page: 1,
        rows: 20
      },
      statistics: {} as any,
      orchestraInfo: {} as any // 乐团详情
    })

    // 选择学期
    const onSelect = (val: any) => {
      state.actionTerm.forEach((item: any) => {
        item.selected = false
      })
      val.selected = true
      state.actionText = val.name
      state.actionType = val.value

      if (val.value === 'up') {
        state.params.startTime = dayjs(Number(state.currentData[0]) + startTime.value).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        state.params.endTime = dayjs(Number(state.currentData[0]) + endTime.value)
          .add(1, 'year')
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      } else if (val.value === 'down') {
        state.params.startTime = dayjs(Number(state.currentData[0]) + endTime.value)
          .add(1, 'year')
          .format('YYYY-MM-DD HH:mm:ss')
        state.params.endTime = dayjs(Number(state.currentData[0]) + startTime.value)
          .add(1, 'year')
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      }
      state.oPopover = false
      onSearch()
    }

    const onConfirmDate = (date: any) => {
      state.currentData = date.selectedValues

      const year = Number(state.currentData[0]) + 1
      if (state.actionType === 'up') {
        state.params.startTime = dayjs(year + startTime.value).format('YYYY-MM-DD HH:mm:ss')
        state.params.endTime = dayjs(year + endTime.value)
          .add(1, 'year')
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      } else if (state.actionType === 'down') {
        state.params.startTime = dayjs(year + endTime.value).format('YYYY-MM-DD HH:mm:ss')
        state.params.endTime = dayjs(year + startTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      }
      state.timeShow = false
      onSearch()
    }

    const getDetails = async () => {
      try {
        const { data } = await request.get('/api-school/orchestra/detail/' + route.query.id)
        state.orchestraInfo = data || {}
      } catch {
        //
      }
    }

    const getStatistics = async () => {
      try {
        const { data } = await request.post('/api-school/school/schoolSummaryStat', {
          data: {
            orchestraId: route.query.id
          }
        })
        state.statistics = data || {}

        initNumCountUp()
      } catch {
        //
      }
    }

    // 班级列表
    const getList = async () => {
      try {
        if (state.isLoading) return
        state.isLoading = true
        const res = await request.post('/api-school/classGroup/page', {
          data: {
            ...state.params,
            orchestraId: route.query.id
          }
        })
        state.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (state.list.length > 0 && result.current === 1) {
          return
        }
        const rows = result.rows || []
        state.list = state.list.concat(rows)
        state.listState.finished = result.current >= result.pages
        state.params.page = result.current + 1
        state.listState.dataShow = state.list.length > 0
        state.isLoading = false
      } catch {
        state.listState.dataShow = false
        state.listState.finished = true
        state.isLoading = false
      }
    }

    const onSearch = () => {
      state.params.page = 1
      state.list = []
      state.listState.dataShow = true // 判断是否有数据
      state.listState.loading = false
      state.listState.finished = false
      getList()
    }

    const initNumCountUp = () => {
      nextTick(() => {
        // 在读学员
        const statistics = state.statistics
        new CountUp('currentStudentNum', statistics.currentStudent || 0).start()
        new CountUp('time1', statistics.attendanceRate * 100 || 0).start()
        new CountUp('time2', statistics.homeworkSubmissionRate * 100 || 0).start()
        new CountUp('time3', statistics.practicePassRate * 100 || 0).start()
      })
    }

    onMounted(async () => {
      const sysStartTime = dayjs(dayjs().year() + startTime.value).format('YYYY-MM-DD')
      const sysEndTime = dayjs(dayjs().year() + endTime.value).format('YYYY-MM-DD')
      const nowTime = dayjs().format('YYYY-MM-DD')
      console.log(nowTime, sysStartTime)
      const before = dayjs(nowTime).isBefore(dayjs(sysStartTime))
      const after = dayjs(nowTime).isBefore(dayjs(sysEndTime))
      const year = dayjs().year()

      // console.log(before, after, year)
      if (before && after) {
        state.currentData = [year - 1 + '']
        state.params.startTime = dayjs(year - 1 + startTime.value).format('YYYY-MM-DD HH:mm:ss')
        state.params.endTime = dayjs(dayjs().year() + endTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
        // 上学期
      }

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

      if (before && !after) {
        state.params.startTime = dayjs(year + endTime.value).format('YYYY-MM-DD HH:mm:ss')
        state.params.endTime = dayjs(year + startTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')

        // 下学期
        state.actionTerm.forEach((item: any) => {
          if (item.value === 'down') {
            item.color = 'var(--van-primary-color)'
            state.actionText = item.text
            state.actionType = item.value
          } else {
            item.color = ''
          }
        })
        state.currentData = [year - 1 + '']
        state.actionText = '下学期'
        state.actionType = 'down'
        state.actionTerm.forEach((item: any) => {
          if (item.value === 'down') {
            item.selected = true
          } else {
            item.selected = false
          }
        })
      }

      await getDetails()
      await getStatistics()
      await getList()
    })

    return () => (
      <>
        <div class={['searchGroup', 'van-hairline--top']}>
          <div
            class={['searchItem', state.timeShow ? 'searchItem-active' : '']}
            onClick={() => (state.timeShow = true)}
          >
            {state.currentData[0]}年 <i class={'arrow'}></i>
          </div>
          <div
            class={['searchItem', state.oPopover ? 'searchItem-active' : '']}
            onClick={() => (state.oPopover = true)}
          >
            {state.actionText} <i class={'arrow'}></i>
          </div>
        </div>

        <div
          style={{
            height: `calc(100vh - var(--header-height) - var(--van-tabs-line-height)  - 1.17333rem)`,
            overflow: 'hidden',
            overflowY: 'auto'
          }}
        >
          <Grid border={false} class={styles.gridContainer}>
            <GridItem>
              <p class={[styles.title, styles.red]}>
                <span id="currentStudentNum">{state.statistics.studentNum || 0}</span>
                <i> 名</i>
              </p>
              <p class={styles.name}>在读学员</p>
            </GridItem>
            <GridItem>
              <p class={[styles.title, styles.red]}>
                <span id="time1">{state.statistics.attendanceRate || 0}</span>%
              </p>
              <p class={styles.name}>到课率</p>
            </GridItem>
            <GridItem>
              <p class={[styles.title, styles.red]}>
                <span id="time2">{state.statistics.homeworkRate || 0}</span>%
              </p>
              <p class={styles.name}>作业提交率</p>
            </GridItem>
            <GridItem>
              <p class={[styles.title, styles.red]}>
                <span id="time3">{state.statistics.homeworkQualifiedRate || 0}</span>%
              </p>
              <p class={styles.name}>练习合格率</p>
            </GridItem>
          </Grid>

          {state.listState.dataShow ? (
            <List
              // v-model:loading={state.listState.loading}
              finished={state.listState.finished}
              finishedText=" "
              class={[styles.liveList]}
              onLoad={getList}
              immediateCheck={false}
            >
              {state.list.map((item: any) => (
                <div class={[styles.gridContainer, styles.gridClass]}>
                  <div class={styles.className}>
                    <i class={styles.line}></i>
                    {item.name}
                  </div>
                  <Grid border={false} columnNum={3}>
                    <GridItem>
                      <p class={styles.title}>{item.preStudentNum || 0}</p>
                      <p class={styles.name}>在读学员</p>
                    </GridItem>
                    <GridItem>
                      <p class={[styles.title, styles.teacher, 'van-ellipsis']}>
                        {item.teacherName || '-'}
                      </p>
                      <p class={styles.name}>伴学老师</p>
                    </GridItem>
                    <GridItem>
                      <p class={styles.title}>
                        {item.completeCourseScheduleNum || 0}/{item.courseScheduleNum || 0}
                      </p>
                      <p class={styles.name}>课时</p>
                    </GridItem>
                  </Grid>
                </div>
              ))}
            </List>
          ) : (
            <OEmpty btnStatus={false} tips="暂无班级" />
          )}
          {/*  */}
          {state.orchestraInfo.canSignUp && (
            // <Teleport to={'body'}>
            <OSticky
              position="bottom"
              class={styles.informationBottom}
              onGetHeight={(height: any) => {
                state.bottomHeight = height
              }}
            >
              <div class={'btnGroup'}>
                <Button
                  round
                  block
                  type="primary"
                  onClick={() => {
                    router.push({
                      path: 'save-share-image',
                      query: {
                        type: 'orchestra',
                        id: route.query.id
                      }
                    })
                  }}
                >
                  报名二维码
                </Button>
              </div>
            </OSticky>
            // </Teleport>
          )}
        </div>

        <OActionSheet
          v-model:show={state.oPopover}
          actions={state.actionTerm}
          onSelect={onSelect}
          teleport={'body'}
        />

        <Popup
          v-model:show={state.timeShow}
          position="bottom"
          round
          class={'popupBottomSearch'}
          teleport={'body'}
        >
          <DatePicker
            v-model={state.currentData}
            columnsType={['year']}
            formatter={formatterDatePicker}
            onConfirm={onConfirmDate}
            onCancel={() => (state.timeShow = false)}
          />
        </Popup>
      </>
    )
  }
})
