import request from '@/helpers/request'
import {
  Button,
  Cell,
  CellGroup,
  DatePicker,
  DatePickerColumnType,
  List,
  Picker,
  Popup
} from 'vant'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import styles from '../index.module.less'
import { state as baseState } from '@/state'
import iconOrchestra from '@/views/mine-orchestra/images/icon-or.png'
import OEmpty from '@/components/o-empty'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { formatterDatePicker } from '@/helpers/utils'
import OFullRefresh from '@/components/o-full-refresh'

export default defineComponent({
  name: 'train-list',
  props: {
    type: {
      type: String,
      default: 'WEEKLY'
    },
    orchestraList: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const columnsType = ref<DatePickerColumnType[]>(['year', 'month'])
    const router = useRouter()
    const state = reactive({
      showPopoverTime: false,
      timeName: dayjs().format('YYYY') + '年' + dayjs().format('MM') + '月',
      currentDate: [dayjs().format('YYYY'), dayjs().format('MM')],
      orchestraStatus: false,
      selectOrchestra: {} as any,
      isClick: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      params: {
        page: 1,
        rows: 20
      }
    })

    const getList = async () => {
      try {
        if (state.isClick) return
        state.isClick = true

        const dateRange = dayjs(state.currentDate[0] + '-' + state.currentDate[1] + '01')
        const startTime = dateRange.startOf('month').format('YYYY-MM-DD')
        const endTime = dateRange.endOf('month').format('YYYY-MM-DD')
        const { data } = await request.post('/api-school/orchestraReport/page', {
          data: {
            reportType: props.type,
            page: state.params.page,
            rows: state.params.rows,
            orchestraId: state.selectOrchestra.value,
            startTime,
            endTime
          }
        })

        state.listState.loading = false
        state.listState.refreshing = false
        // 处理重复请求数据
        if (state.list.length > 0 && data.current === 1) {
          return
        }
        state.list = state.list.concat(data.rows || [])
        state.listState.finished = data.current >= data.pages
        state.params.page = data.current + 1
        state.listState.dataShow = state.list.length > 0
        state.isClick = false
      } catch {
        state.listState.dataShow = false
        state.listState.finished = true
        state.listState.refreshing = false
        state.isClick = false
      }
    }

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

    const onDetail = (item: any) => {
      const path = props.type === 'WEEKLY' ? '/train-week-report' : '/train-month-report'
      router.push({
        path,
        query: {
          id: item.id
        }
      })
    }

    const checkTimer = (val: any) => {
      state.timeName = val.selectedValues[0] + '年' + val.selectedValues[1] + '月'
      state.showPopoverTime = false
      onRefresh()
    }

    onMounted(async () => {
      try {
        // 判断是否有乐团
        if (props.orchestraList.length > 0) {
          // const orchestraId = sessionStorage.getItem('orchestraStoryId')
          // if (orchestraId) {
          //   const item = props.orchestraList.find((child: any) => child.value === orchestraId)
          //   state.selectOrchestra = item || props.orchestraList[0]
          // } else {
          state.selectOrchestra = props.orchestraList[0]
          // }
        }

        await getList()
      } catch {
        //
      }
    })

    return () => (
      <div
        style={{
          minHeight: 'calc(100vh  - var(--van-tabs-line-height))',
          overflow: 'hidden'
        }}
      >
        <div class={'searchGroup'}>
          <div
            class={['searchItem', state.showPopoverTime && 'searchItem-active']}
            onClick={() => {
              state.showPopoverTime = true
            }}
          >
            {state.timeName}
            <i class={'arrow'}></i>
          </div>
          <div
            class={['searchItem', state.orchestraStatus && 'searchItem-active']}
            onClick={() => {
              state.orchestraStatus = true
            }}
          >
            <span>{state.selectOrchestra.text || ' '}</span>
            <i class={'arrow'}></i>
          </div>
        </div>
        <div
          style={{
            overflowY: 'auto',
            height: 'calc(100vh - var(--van-tabs-line-height)  - 1.17333rem)'
          }}
        >
          {state.listState.dataShow ? (
            <OFullRefresh
              v-model:modelValue={state.listState.refreshing}
              onRefresh={onRefresh}
              style={{
                minHeight: 'calc(100vh - var(--van-tabs-line-height)  - 1.17333rem)'
              }}
            >
              <List
                // v-model:loading={state.listState.loading}
                finished={state.listState.finished}
                finishedText=" "
                style={{
                  overflow: 'hidden'
                }}
                onLoad={getList}
                immediateCheck={false}
              >
                {state.list.map((item: any) => (
                  <Cell center class={styles.reportList}>
                    {{
                      title: () => <div>{item.orchestraName}</div>,
                      value: () => (
                        <Button type="primary" round size="small" onClick={() => onDetail(item)}>
                          查看报告
                        </Button>
                      ),
                      label: () =>
                        props.type === 'WEEKLY' ? (
                          <div class={styles.time}>
                            {item.startTime}~{item.endTime}
                          </div>
                        ) : (
                          <div class={styles.time}>{item.monthlyTime}</div>
                        )
                    }}
                  </Cell>
                ))}
              </List>
            </OFullRefresh>
          ) : (
            <OEmpty btnStatus={false} tips="暂无训练报告" />
          )}
        </div>

        <Popup
          v-model:show={state.showPopoverTime}
          position="bottom"
          round
          teleport={'body'}
          class={'popupBottomSearch'}
        >
          <DatePicker
            onCancel={() => {
              state.showPopoverTime = false
            }}
            onConfirm={checkTimer}
            v-model={state.currentDate}
            formatter={formatterDatePicker}
            columnsType={columnsType.value}
          />
        </Popup>

        <Popup
          v-model:show={state.orchestraStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}
          teleport="body"
        >
          <Picker
            columns={props.orchestraList as any}
            onCancel={() => (state.orchestraStatus = false)}
            onConfirm={(val: any) => {
              state.selectOrchestra = val.selectedOptions[0]
              state.orchestraStatus = false
              onRefresh()
            }}
          />
        </Popup>
      </div>
    )
  }
})
