import OHeader from '@/components/o-header'
import {
  Cell,
  CellGroup,
  Icon,
  Image,
  List,
  Picker,
  Popup,
  Step,
  Steps,
  Swipe,
  SwipeItem
} from 'vant'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'
import iconEdit from './images/icon-edit.png'
import iconStep from './images/icon-step.png'
import iconStepCalendar from './images/icon-step-calendar.png'
import request from '@/helpers/request'
import { state as baseState } from '@/state'
import OFullRefresh from '@/components/o-full-refresh'
import OEmpty from '@/components/o-empty'
import dayjs from 'dayjs'
import OVideo from '@/components/o-video'
import baseEvent from '@/base-event'
import iconOrchestra from '@/views/mine-orchestra/images/icon-or.png'

export default defineComponent({
  name: 'orchestra-story',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      orchestraStatus: false,
      orchestraList: [] as any,
      selectOrchestra: {} as any,
      isClick: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      params: {
        type: null,
        page: 1,
        rows: 20
      }
    })

    // 获取乐团列表
    const getOrchestras = async () => {
      try {
        const { data } = await request.post('/api-school/orchestra/page', {
          data: {
            page: 1,
            rows: 100,
            schoolId: baseState.user.data.school.id,
            status: 'DONE'
          }
        })
        const temps = data.rows || []
        const s = [] as any
        temps.forEach((item: any) => {
          s.push({
            text: item.name,
            value: item.id
          })
        })
        state.orchestraList = [...s]

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

          getList()
        }
      } catch {
        //
      }
    }

    const getList = async () => {
      try {
        if (state.isClick) return
        state.isClick = true
        const res = await request.post('/api-school/orchestraStory/page', {
          data: {
            orchestraId: state.selectOrchestra.value
          }
        })
        state.listState.loading = false
        state.listState.refreshing = false
        const result = res.data || {}
        // 处理重复请求数据
        if (state.list.length > 0 && result.current === 1) {
          return
        }
        state.list = state.list.concat(result.rows || [])
        state.listState.finished = result.current >= result.pages
        state.params.page = result.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 onEdit = async (item: any) => {
      router.push({
        path: '/story-operation',
        query: {
          id: item.id,
          orchestraId: state.selectOrchestra.value
        }
      })
    }

    const videoRef: any = ref([])
    const onPlay = (index: any) => {
      videoRef.value.forEach((item: any, child: any) => {
        if (child !== index) {
          item.onStop()
        }
      })
    }

    onMounted(async () => {
      getOrchestras()
    })
    return () => (
      <div class={[styles.orchestraStory, !state.listState.dataShow && 'emptyRootContainer']}>
        <OHeader>
          {{
            right: () => (
              <span
                style={{ color: 'var(--van-primary)', fontWeight: 500 }}
                onClick={() => {
                  router.push('/story-operation')
                }}
              >
                添加
              </span>
            )
          }}
        </OHeader>

        {state.orchestraList.length > 0 && (
          <div style={{ width: '100%' }}>
            <CellGroup inset class={styles.cellGroup}>
              <Cell
                isLink
                center
                onClick={() => (state.orchestraStatus = true)}
                class={styles.select}
              >
                {{
                  icon: () => <img class={styles.icon} src={iconOrchestra} />,
                  title: () => <div class="van-ellipsis">{state.selectOrchestra.text || ' '}</div>
                }}
              </Cell>
            </CellGroup>
          </div>
        )}

        {state.listState.dataShow ? (
          // <OFullRefresh
          //   v-model:modelValue={state.listState.refreshing}
          //   onRefresh={onRefresh}
          //   style={{
          //     minHeight: `calc(100vh - ${state.listState.height}px)`
          //   }}
          // >
          <List
            // v-model:loading={state.listState.loading}
            finished={state.listState.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            immediateCheck={false}
          >
            <Steps direction="vertical" class={styles.storySteps}>
              {state.list.map((item: any, index: number) => (
                <Step
                  v-slots={{
                    'inactive-icon': () => <Image src={iconStep} class={styles.iconInactive} />,
                    'active-icon': () => <Image src={iconStepCalendar} class={styles.iconActive} />
                  }}
                >
                  <div class={styles.stepTimes}>
                    <div class={styles.stepTime}>
                      {dayjs(item.createTime).format('YYYY年MM月DD日')}
                    </div>
                    <span class={styles.stepEdit} onClick={() => onEdit(item)}>
                      <Icon name={iconEdit} />
                      编辑
                    </span>
                  </div>
                  <p class={[styles.content, 'van-multi-ellipsis--l2']}>{item.content}</p>

                  <Swipe class={styles.storySwipe}>
                    {item.attachments &&
                      item.attachments.map((child: any) => (
                        <SwipeItem>
                          {item.type === 'IMAGE' && (
                            <div
                              class={styles.swipeImg}
                              style={
                                child.url
                                  ? {
                                      backgroundImage: `url(${child.url})`,
                                      backgroundSize: 'cover'
                                    }
                                  : ''
                              }
                            ></div>
                          )}
                          {item.type === 'VIDEO' && (
                            <OVideo
                              // ref={videoRef}
                              ref={(el: any) => (videoRef.value[index] = el)}
                              src={child.url}
                              height={'100%'}
                              poster={child.coverImage}
                              class={styles.swipeImg}
                              onPlay={() => onPlay(index)}
                            />
                          )}
                        </SwipeItem>
                      ))}
                  </Swipe>
                </Step>
              ))}
            </Steps>
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无事迹" />
        )}

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