import OEmpty from '@/components/o-empty'
import OHeader from '@/components/o-header'
import request from '@/helpers/request'
import { state } from '@/state'
import {
  Cell,
  CellGroup,
  Grid,
  GridItem,
  Image,
  List,
  Loading,
  Picker,
  Popup,
  showImagePreview
} from 'vant'
import { defineComponent, onMounted, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'
import iconImage from '../images/icon-photo-default.png'
import iconOrchestra from '../images/icon-or.png'
import OSticky from '@/components/o-sticky'
import OFullRefresh from '@/components/o-full-refresh'
export default defineComponent({
  name: 'photo-detail',
  props: {
    orchestraId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()
    const data = reactive({
      refreshing: false,
      loading: false,
      finished: false,
      pages: {
        page: 1,
        rows: 20
      },
      list: [] as any[],
      schoolStatus: false,
      schoolList: [],
      school: {} as any
    })

    const getList = async () => {
      if (data.refreshing) {
        data.pages.page = 1
        data.finished = false
        data.list = []
      }
      data.loading = true
      try {
        const res = await request.post(`${state.platformApi}/orchestraPhotoAlbum/page`, {
          data: {
            ...data.pages,
            schoolId: data.school.id
          },
          hideLoading: true
        })
        if (Array.isArray(res?.data?.rows)) {
          data.list = data.list.concat(res.data.rows)
          data.pages.page += 1
          if (!res.data.rows.length) {
            data.finished = true
          }
        }
      } catch {
        data.finished = true
      }
      data.loading = false
      setTimeout(() => {
        data.refreshing = false
      }, 500)
    }

    const getSchoolList = async () => {
      try {
        const res = await request.post('/api-teacher/school/teacherSchoolPage', {
          data: {
            teacherId: state.user.data.id,
            page: 1,
            rows: 999
          }
        })
        if (Array.isArray(res.data?.rows)) {
          data.schoolList = res.data.rows.map((n: any) => {
            return {
              name: n.schoolName || '',
              id: n.schoolId || ''
            }
          })
          data.school = data.schoolList[0] || {}
        }
      } catch {
        //
      }
    }

    // 预览图片
    const onShowImage = (index: number) => {
      const files = data.list.map((file: any) => {
        return file.fileUrl
      })

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

    onMounted(async () => {
      await getSchoolList()
      await getList()
      document.title = (route.query.name as any) || ''
    })

    return () => (
      <div>
        <OSticky
          onGetHeight={(height: number) => {
            document.documentElement.style.setProperty('--header-height', height + 'px')
          }}
        >
          <OHeader />
        </OSticky>

        {data.schoolList.length > 0 && (
          <OSticky
            offsetTop={`var(--header-height)`}
            onGetHeight={(height: number) => {
              document.documentElement.style.setProperty('--header-cellGroup', height + 'px')
            }}
          >
            <div
              style={{
                overflow: 'hidden'
              }}
            >
              <CellGroup inset class={styles.cellGroup}>
                <Cell
                  class={styles.select}
                  center
                  isLink
                  onClick={() => (data.schoolStatus = true)}
                >
                  {{
                    icon: () => <img class={styles.icon} src={iconOrchestra} />,
                    title: () => <div class="van-ellipsis">{data.school.name}</div>
                  }}
                </Cell>
              </CellGroup>
            </div>
          </OSticky>
        )}

        <OFullRefresh v-model={data.refreshing} onRefresh={() => getList()}>
          <div class={[styles.phoneDetail]}>
            {!data.loading && !!data.list.length && (
              <List
                loading={data.loading}
                finished={data.finished}
                finishedText="没有更多数据"
                onLoad={getList}
                immediateCheck={false}
              >
                <div class={styles.photoWrap}>
                  {data.list.map((item: any, index: number) => (
                    <div
                      class={styles.photoItem}
                      onClick={() => {
                        router.push({
                          path: '/photo-list',
                          query: {
                            id: item.id,
                            name: item.name
                          }
                        })
                      }}
                    >
                      <div class={styles.imgSection}>
                        <div
                          class={styles.gridImg}
                          style={
                            item.coverUrl
                              ? {
                                  backgroundImage: `url(${item.coverUrl})`,
                                  backgroundSize: 'cover'
                                }
                              : ''
                          }
                        >
                          {item.newFlag ? <i class={styles.iconNew}></i> : ''}
                        </div>
                      </div>

                      <div class={[styles.gridName, 'van-ellipsis']}>{item.name}</div>
                      <div class={styles.gridDes}>{item.photoCount}张</div>
                    </div>
                  ))}
                </div>
              </List>
            )}
            {!data.loading && !data.list.length && (
              <div
                class="emptyRootContainer"
                style={{
                  minHeight: '78%'
                }}
              >
                <OEmpty btnStatus={false} tips="暂无相册" />
              </div>
            )}

            <Popup
              v-model:show={data.schoolStatus}
              position="bottom"
              round
              class={'popupBottomSearch'}
            >
              <Picker
                columns={data.schoolList}
                columnsFieldNames={{ text: 'name', value: 'id' }}
                onCancel={() => (data.schoolStatus = false)}
                onConfirm={({ selectedValues }: any) => {
                  const val = selectedValues[0] || ''
                  data.schoolStatus = false
                  if (val == data.school?.id) {
                    return
                  }
                  const active = data.schoolList.find((n: any) => n.id == val) || {}
                  data.school = active

                  data.pages.page = 1
                  data.list = []
                  data.finished = false
                  getList()
                }}
              />
            </Popup>
          </div>
        </OFullRefresh>
      </div>
    )
  }
})
