import OEmpty from '@/components/o-empty'
import OHeader from '@/components/o-header'
import request from '@/helpers/request'
import { Image, List, showImagePreview } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import styles from './index.module.less'

export default defineComponent({
  name: 'photo-detail',
  setup() {
    const route = useRoute()
    const state = reactive({
      isEdit: false,
      isLoading: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      }
    })

    const getList = async () => {
      try {
        if (state.isLoading) return
        state.isLoading = true
        const res = await request.post('/api-school/orchestraPhoto/page', {
          data: {
            ...state.params,
            orchestraPhotoAlbumId: route.query.photoId
          }
        })
        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 onShowImage = (index: number) => {
      const files = state.list.map((file: any) => {
        return file.fileUrl
      })

      showImagePreview({
        images: files,
        startPosition: index,
        closeable: true
      })
    }

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

    return () => (
      <div class={styles.phoneDetail}>
        <OHeader title={(route.query.name as any) || ''}></OHeader>

        {state.listState.dataShow ? (
          <List
            v-model:loading={state.listState.loading}
            finished={state.listState.finished}
            finishedText=" "
            onLoad={getList}
            immediateCheck={false}
          >
            <div class={styles.phoneContainer}>
              {state.list.map((item: any, index: number) => (
                <div
                  class={[styles.item]}
                  onClick={() => {
                    onShowImage(index)
                  }}
                >
                  <Image class={styles.img} src={item.fileUrl} fit="cover" />
                </div>
              ))}
            </div>
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无相片" />
        )}
      </div>
    )
  }
})
