import dayjs from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)
import { List, Image, Calendar, Cell } from 'vant'
import OFullRefresh from '@/components/the-full-refresh'
import DetailItem from './modals/detail-item'
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  computed,
  markRaw,
  nextTick
} from 'vue'
import { useRoute } from 'vue-router'
import styles from './exercis-detail.module.less'
import request from '@/helpers/request'
import { state as baseState } from '@/state'
import TheSticky from '@/components/the-sticky'
import ColHeader from '@/components/col-header'
import ColResult from '@/components/col-result'
import bgImg from '../images/bg-image-1.png'
import iconStudent from '@common/images/icon_student.png'
import iconLogo from '../member-center/images/icon-logo-default.png'
import iconLogoActive from '../member-center/images/icon-logo.png'
import iconSubject from './images/icon-subject.png'
import iconTrainTitle from './images/train-title.png'

import * as echarts from 'echarts/core'
import {
  BarChart,
  // 系列类型的定义后缀都为 SeriesOption
  BarSeriesOption,
  LineChart,
  LineSeriesOption
} from 'echarts/charts'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  // 组件类型的定义后缀都为 ComponentOption
  TitleComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  // 数据集组件
  DatasetComponent,
  DatasetComponentOption,
  // 内置数据转换器组件 (filter, sort)
  TransformComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { lineChartOption } from './echats'

// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = echarts.ComposeOption<
  | BarSeriesOption
  | LineSeriesOption
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | DatasetComponentOption
>

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  PieChart,
  ToolboxComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart
])

export default defineComponent({
  name: 'exercis-detail',
  setup() {
    const route = useRoute()
    const state = reactive({
      showPopoverTime: false,
      currentDate: [dayjs().format('YYYY'), dayjs().format('MM')],
      isClick: false,
      practiceMonthName: route.query.practiceMonthName
        ? route.query.practiceMonthName
        : dayjs().format('YYYY') + '年' + dayjs().format('MM') + '月',
      userTrainOverView: {
        trainDays: 0,
        trainNum: 0,
        trainTime: 0,
        avgTrainTime: 0
      },
      userTrainChartData: [] as any,
      myChart: null as any
    })
    const qualifiedFlag = ref(true)
    const unqualifiedFlag = ref(true)

    // const chartRef = ref<HTMLDivElement | null>(null)
    // const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>)

    const userInfo = computed(() => {
      const users = baseState.user.data
      return {
        username: users?.username,
        phone: users?.phone,
        avatar: users?.heardUrl,
        id: users?.userId,
        subjectName: users?.subjectName,
        memberRankSettingId: users?.memberRankSettingId,
        isVip: users?.isVip,
        membershipDays: users?.membershipDays,
        membershipEndTime: users?.membershipEndTime
      }
    })

    // 初始化周一
    const formatWeekDays = (time?: any) => {
      const week = dayjs(time).day()
      let startTime = ''
      let endTime = ''
      if (week === 0) {
        // 星期天
        startTime = dayjs(time).subtract(6, 'day').format('YYYY-MM-DD')
        endTime = dayjs(time).format('YYYY-MM-DD')
      } else if (week === 1) {
        // 星期一
        startTime = dayjs(time).format('YYYY-MM-DD')
        endTime = dayjs(time).add(6, 'day').format('YYYY-MM-DD')
      } else {
        startTime = dayjs(time)
          .subtract(week - 1, 'day')
          .format('YYYY-MM-DD')
        endTime = dayjs(time)
          .add(7 - week, 'day')
          .format('YYYY-MM-DD')
      }
      return {
        startTime,
        endTime
      }
    }

    const forms = reactive({
      ...formatWeekDays(),
      page: 1,
      rows: 20
    })

    const refreshing = ref(false)
    const loading = ref(false)
    const finished = ref(false)
    const showContact = ref(false)
    const list = ref([])
    const getList = async () => {
      if (state.isClick) {
        return
      }
      state.isClick = true
      if (refreshing.value) {
        list.value = []
        forms.page = 1
        refreshing.value = false
      }
      try {
        const { data } = await request.get(
          `/api-student/sysMusicRecord/studentTrainDataByWeek`,
          {
            params: { ...forms }
          }
        )

        // 在第一页的时候才处理数据显示
        if (data.detail.pageNo === 1) {
          state.userTrainOverView = data.userTrainOverView
        }
        if (list.value.length > 0 && data.detail.pageNo === 1) {
          return
        }
        state.userTrainChartData = data.userTrainChartData || []
        list.value = list.value.concat(data.detail.rows || [])
        forms.page = data.detail.pageNo + 1
        showContact.value = list.value.length > 0
        loading.value = false
        finished.value = data.detail.pageNo >= data.detail.totalPage
      } catch {
        showContact.value = false
        finished.value = true
      }
      state.isClick = false

      // if (showContact.value) {
      nextTick(() => {
        if (document.getElementById('exerciseWeek')) {
          state.myChart = markRaw(
            echarts.init(
              document.getElementById('exerciseWeek') as HTMLDivElement
            )
          )

          const cloudTime: any = []
          const cloudNum: any = []
          state.userTrainChartData.forEach((data: any) => {
            const indexData = data.indexMonthData || []
            if (data.dataType === 'CLOUD_STUDY_TRAIN_TIME') {
              indexData.forEach((d: any) => {
                cloudTime.push(d.percent)
              })
            } else if (data.dataType === 'CLOUD_STUDY_TRAIN_NUM') {
              indexData.forEach((d: any) => {
                cloudNum.push(d.percent)
              })
            }
          })
          lineChartOption.series[0].data = cloudTime
          lineChartOption.series[1].data = cloudNum

          state.myChart.clear()
          state.myChart.setOption(lineChartOption)
        }
      })
      // }
    }
    const onRefresh = () => {
      finished.value = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true
      getList()
    }

    onMounted(async () => {
      await getList()
    })

    return () => (
      <div class={[styles.exercisContainer]}>
        <div class={styles.topWrap}>
          <TheSticky position="top">
            <ColHeader border={false} background={'transparent'} />
            <Cell
              class={styles.userMember}
              labelClass={styles.timeRemaining}
              border={false}
              v-slots={{
                icon: () => (
                  <div class={styles.userImgSection}>
                    <Image
                      class={styles.userImg}
                      src={userInfo.value.avatar || iconStudent}
                      fit="cover"
                    />
                  </div>
                ),
                title: () => (
                  <div class={styles.userInfo}>
                    <span class={styles.name}>{userInfo.value.username}</span>
                    {/* <Image
                      class={styles.level}
                      src={userInfo.value.isVip ? iconLogoActive : iconLogo}
                    /> */}
                  </div>
                ),
                label: () => (
                  <div class={styles.subjectName}>
                    <span class={styles.subjectTag}>
                      <img src={iconSubject} class={styles.iconSubject} />
                      <div class={styles.name}>{userInfo.value.subjectName}</div>
                    </span>
                  </div>
                )
              }}
            ></Cell>

            <div class={styles.itemBottom}>
              <div class={styles.itemBottomDot}>
                <p class={styles.dotMain}>
                  {state.userTrainOverView.trainTime || 0}
                  <span>分钟</span>{' '}
                </p>
                <p class={styles.dotSub}> 累计练习时长</p>
              </div>
              <div class={styles.itemBottomDot}>
                <p class={styles.dotMain}>
                  {state.userTrainOverView.trainDays || 0}
                  <span>天</span>{' '}
                </p>
                <p class={styles.dotSub}>累计练习天数 </p>
              </div>
              <div class={styles.itemBottomDot}>
                <p class={styles.dotMain}>
                  {state.userTrainOverView.avgTrainTime || 0}
                  <span>分钟</span>{' '}
                </p>
                <p class={styles.dotSub}>平均训练时长 </p>
              </div>
              <div class={styles.itemBottomDot}>
                <p class={styles.dotMain}>
                  {state.userTrainOverView.trainNum || 0}
                  <span>次</span>{' '}
                </p>
                <p class={styles.dotSub}>累计训练次数 </p>
              </div>
            </div>
          </TheSticky>
        </div>
        <img class={styles.bgImg} src={bgImg} />

        <div class={styles.trainWeek}>
          <div class={styles.trainTitle}>
            <img src={iconTrainTitle} />

            <span
              class={styles.timeRange}
              onClick={() => (state.showPopoverTime = true)}
            >
              {dayjs(forms.startTime).format('YYYY-MM-DD')}至
              {dayjs(forms.endTime).format('YYYY-MM-DD')}
              <i class={styles.iconArrow}></i>
            </span>
          </div>
          <div class={styles.TrainDataTopRight}>
            <div
              onClick={() => {
                qualifiedFlag.value = !qualifiedFlag.value
                lineChartOption.legend.selected['训练时长'] =
                  qualifiedFlag.value
                state.myChart.setOption(lineChartOption)
              }}
              class={[
                styles.DataTopRightItem,
                qualifiedFlag.value ? '' : styles.DataTopRightItemDis
              ]}
            >
              <div class={styles.DataTopRightDot}></div>
              <p>训练时长</p>
            </div>
            <div
              onClick={() => {
                unqualifiedFlag.value = !unqualifiedFlag.value
                lineChartOption.legend.selected['使用次数'] =
                  unqualifiedFlag.value
                state.myChart.setOption(lineChartOption)
              }}
              class={[
                styles.DataTopRightItem,
                unqualifiedFlag.value ? '' : styles.DataTopRightItemDis
              ]}
            >
              <div class={[styles.DataTopRightDot, styles.red]}></div>
              <p>使用次数</p>
            </div>
          </div>
          <div id="exerciseWeek" class={styles.exerciseWeek}></div>
        </div>
        {showContact.value ? (
          <OFullRefresh
            v-model:modelValue={refreshing.value}
            onRefresh={onRefresh}
            class={styles.fullRefresh}
          >
            <List
              loading-text=" "
              finished={finished.value}
              finished-text=" "
              onLoad={getList}
              style={{ overflow: 'hidden' }}
            >
              {list.value.map((item: any) => (
                <DetailItem item={item} />
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <div
            // style={{
            //   height: `calc(100vh - var(--header-height))`,
            //   display: 'flex',
            //   alignItems: 'center'
            // }}
            class={styles.emptyContainer}
          >
            <ColResult
              tips="暂无学练统计"
              // classImgSize="SMALL"
              btnStatus={false}
            />
          </div>
        )}

        <Calendar
          v-model:show={state.showPopoverTime}
          firstDayOfWeek={1}
          showConfirm={false}
          type="range"
          title="周期选择"
          maxRange={7}
          minDate={new Date('2023-02-27')}
          defaultDate={[
            dayjs(forms.startTime).toDate(),
            dayjs(forms.endTime).toDate()
          ]}
          style={{
            height: '70%'
          }}
          onSelect={(item: any) => {
            forms.startTime = ''
            forms.endTime = ''
            if (
              !dayjs(item[0]).isBetween(
                dayjs(forms.startTime),
                dayjs(forms.endTime)
              )
            ) {
              const times = formatWeekDays(item[0])
              forms.startTime = times.startTime
              forms.endTime = times.endTime
              // if (week === 0) {
              //   // 星期天
              //   forms.startTime = dayjs(item[0])
              //     .subtract(6, 'day')
              //     .format('YYYY-MM-DD')
              //   forms.endTime = dayjs(item[0]).format('YYYY-MM-DD')
              // } else if (week === 1) {
              //   // 星期一
              //   forms.startTime = dayjs(item[0]).format('YYYY-MM-DD')
              //   forms.endTime = dayjs(item[0])
              //     .add(6, 'day')
              //     .format('YYYY-MM-DD')
              // } else {
              //   forms.startTime = dayjs(item[0])
              //     .subtract(week - 1, 'day')
              //     .format('YYYY-MM-DD')
              //   forms.endTime = dayjs(item[0])
              //     .add(7 - week, 'day')
              //     .format('YYYY-MM-DD')
              // }
            }
            state.showPopoverTime = false
            refreshing.value = true
            getList()
          }}
        />
      </div>
    )
  }
})
