import { defineComponent, PropType, reactive, ref } from 'vue'
import styles from './index.module.less'
import { CellGroup, List } from 'vant'
import iconMoney from '../../images/icon-money.png'
import lineBg from '../../images/line-bg.png'
import ColResult from '@/components/col-result'
import Echats from '../echats'
import TeacherItem from '../teacher-item'
import BuyItem from '../buy-item'
import request from '@/helpers/request'
import { getTimeRange } from '../../home-statistics'
import { moneyFormat } from '@/helpers/utils'
import { useRoute } from 'vue-router'

export default defineComponent({
  name: 'list',
  props: {
    type: {
      type: String as PropType<
        'VIP_COURSE' | 'PRACTICE' | 'GROUP' | 'LIVE' | 'VIDEO' | 'MUSIC'
      >,
      default: 'VIP_COURSE'
    },
    accountPeriod: {
      type: Number,
      default: 0
    }
  },
  setup(props) {
    const route = useRoute()
    const timeRange = ref(
      getTimeRange((route.query.currentType as any) || 'MONTH')
    )

    const obj = ref({
      xAxisData: [] as any,
      yAxisData: [] as any,
      countMaxCount: 5,
      browseCount: 0,
      buyCount: 0,
      time: ''
    })

    const dataShow = ref(true) // 判断是否有数据
    const state = reactive({
      statInfo: 0, // 预计课程总收入
      loading: false,
      finished: false,
      params: {
        page: 1,
        rows: 20
      }
    })

    const tableList = ref<any[]>([])

    const getDetail = async () => {
      try {
        const { data } = await request.post(
          '/api-teacher/home/courseExposure',
          {
            data: { ...timeRange.value, type: props.type }
          }
        )

        const buy = data.buy || []
        const exposure = data.exposure || []
        const xAxisData: string[] = []
        const exposureList: number[] = []
        let maxCount = 0 // 最大人数 - 用记设置练习人数分割线
        exposure.forEach((item: any, index: number) => {
          xAxisData.push(item.date)
          exposureList.push(item.exposureNum)

          if (maxCount < (item.exposureNum || 0)) {
            maxCount = item.exposureNum
          }
          if (exposure.length - 1 === index) {
            obj.value.browseCount = item.exposureNum
            obj.value.time = item.date
          }
        })
        const buyList: number[] = []
        buy.forEach((item: any, index: number) => {
          buyList.push(item.exposureNum)

          if (buy.length - 1 === index) {
            obj.value.buyCount = item.exposureNum
          }
        })
        const yAxisData = [exposureList, buyList]
        const countMaxCount = maxCount >= 5 ? 5 : Math.max(maxCount, 1)

        obj.value.xAxisData = xAxisData
        obj.value.yAxisData = yAxisData
        obj.value.countMaxCount = countMaxCount
      } catch {
        //
      }
    }

    const getList = async () => {
      state.loading = true
      try {
        const { data } = await request.post(
          '/api-teacher/home/teacherIncomeList',
          {
            hideLoading: false,
            data: {
              ...timeRange.value,
              type: props.type,
              ...state.params
            }
          }
        )

        state.statInfo = data.statInfo || 0
        tableList.value = tableList.value.concat(data.rows || [])

        state.finished = data.pageNo >= data.totalPage

        state.params.page = data.pageNo + 1
        dataShow.value = tableList.value.length > 0
      } catch {
        dataShow.value = false
        state.finished = true
      }
      state.loading = false
    }

    getDetail()
    getList()

    return () => (
      <div class={styles.list}>
        <Echats
          obj={obj.value}
          currentType={(route.query.currentType as any) || 'MONTH'}
          onConfirm={(val: any) => {
            state.params.page = 1
            tableList.value = []
            timeRange.value = val
            getDetail()
            getList()
          }}
        />

        <div class={styles.expectedIncome}>
          {/* <Sticky> */}
          <div class={styles.incomeTitle}>
            <div class={styles.title}>
              <img src={iconMoney} />
              <span>预计总收入</span>
            </div>

            <div class={styles.price}>
              <span>¥ </span>
              {moneyFormat(state.statInfo || 0)}
            </div>
          </div>
          {/* </Sticky> */}
          <div class={styles.tipSection}>
          {['VIDEO', 'MUSIC'].includes(props.type) ? (
            <div class={styles.incomeTip}>
              实际收入将在学生购买{props.accountPeriod || 1}天后结算
            </div>
          ) : (
            <div class={styles.incomeTip}>
              实际收入将在课程结束{props.accountPeriod || 1}天后结算
            </div>
          )}
          </div>

          <div class={styles.element}>
            <img src={lineBg} />
          </div>
          {dataShow.value ? (
            <List
              v-model:loading={state.loading}
              finished={state.finished}
              finishedText=" "
              immediateCheck={false}
              onLoad={getList}
            >
              <CellGroup class={styles.cellGroup} border={false}>
                {['VIP_COURSE', 'PRACTICE'].includes(props.type) && (
                  <TeacherItem list={tableList.value} />
                )}
                {['GROUP', 'LIVE', 'VIDEO', 'MUSIC'].includes(props.type) && (
                  <BuyItem
                    list={tableList.value}
                    isSquare={props.type === 'MUSIC'}
                  />
                )}
              </CellGroup>
            </List>
          ) : (
            <ColResult
              type="empty"
              btnStatus={false}
              classImgSize="SMALL"
              tips="暂无数据"
            />
          )}
        </div>
      </div>
    )
  }
})
