import OHeader from '@/components/o-header'
import { Cell, CellGroup, Grid, GridItem, Image, List, Picker, Popup, Tag } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'
import iconTeacher from '@common/images/icon_teacher.png'
import iconMessage from '@common/images/icon-message.png'
import { postMessage } from '@/helpers/native-message'
import iconPhoneDefaut from '@/school/orchestra/images/icon-photo-default.png'
import iconChange from './images/icon_change.png'
import request from '@/helpers/request'
import OEmpty from '@/components/o-empty'

export default defineComponent({
  name: 'my-orchestra',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      isLoading: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      },
      orchestraStatus: false,
      orchestraList: [] as any,
      selectOrchestra: {} as any
    })
    const onSearch = () => {
      state.params.page = 1
      state.list = []
      state.listState.dataShow = true // 判断是否有数据
      state.listState.loading = false
      state.listState.finished = false
      getList()
    }

    // 班级列表
    const getList = async () => {
      try {
        if (state.isLoading) return
        state.isLoading = true
        const res = await request.post('/api-student/orchestraPhotoAlbum/page', {
          data: {
            ...state.params,
            orchestraId: state.selectOrchestra.orchestraId
          }
        })
        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 onDetail = (item: any) => {
      router.push({
        path: '/photo-detail',
        query: {
          photoId: item.id,
          name: item.name
        }
      })
    }

    const getOrchestras = async () => {
      try {
        const { data } = await request.post('/api-student/orchestra/studentOrchestra', {})
        console.log(data)
        state.orchestraList = data || []
        if (data && data.length > 0) {
          state.selectOrchestra = data[0]

          console.log(state.selectOrchestra)
          // 判断是否有乐团
          await getList()
        }
      } catch {
        //
      }
    }

    const onMessage = async (item: any) => {
      console.log(item)
      postMessage({
        api: 'joinChatGroup',
        content: {
          type: 'multi', // single 单人 multi 多人
          id: item.imGroupId
        }
      })
    }

    onMounted(async () => {
      await getOrchestras()
    })
    return () => (
      <div class={styles.myOrchestra}>
        <OHeader
          v-slots={{
            right: () => (
              <>
                {(state.selectOrchestra.status === 'REGISTER' ||
                  state.selectOrchestra.status === 'LEARNING') && (
                  <span
                    onClick={() => {
                      router.push({
                        path: '/apply-withdrawal',
                        query: {
                          id: state.selectOrchestra.orchestraId
                        }
                      })
                    }}
                  >
                    申请退团
                  </span>
                )}
                {state.selectOrchestra.status === 'AUTH' && (
                  <span style={{ color: 'red' }}>申请退团中</span>
                )}
                {/* {state.selectOrchestra.status === 'OUTOF_ORCHESTRA' && (
                  <span style={{ color: '#666' }}>已退团</span>
                )} */}
              </>
            )
          }}
        />
        {state.orchestraList.length > 0 ? (
          <>
            <CellGroup inset class={styles.oList}>
              <Cell center clickable>
                {{
                  title: () => (
                    <div class={styles.orchestra}>
                      <i></i>
                      <span class="van-ellipsis">{state.selectOrchestra.orchestraName}</span>
                    </div>
                  ),
                  value: () =>
                    state.selectOrchestra.classGroupIdList &&
                    state.selectOrchestra.classGroupIdList.length > 0 && (
                      <div
                        class={styles.iconChange}
                        onClick={() => {
                          state.orchestraStatus = true
                        }}
                      >
                        切换乐团 <Image src={iconChange} class={styles.img} />
                      </div>
                    )
                }}
              </Cell>
            </CellGroup>
            <div class={[styles.gridContainer, styles.gridClass]}>
              {state.selectOrchestra.classGroupIdList &&
                state.selectOrchestra.classGroupIdList.map((item: any) => (
                  <CellGroup class={styles.classCellGroup}>
                    <Cell
                      center
                      titleStyle={{ flex: '0 auto' }}
                      valueClass={styles.classCheckbox}
                      border={false}
                    >
                      {{
                        icon: () => (
                          <Image src={item.teacherAvatar || iconTeacher} class={styles.img} />
                        ),
                        title: () => (
                          <div class={styles.content}>
                            <div class={styles.teacherName}>
                              <span class={[styles.name, 'van-ellipsis']}>{item.teacherName}</span>
                              <Tag type="primary">{item.classGroupName}</Tag>
                            </div>
                          </div>
                        ),
                        value: () => (
                          <Image
                            class={styles.messageImg}
                            src={iconMessage}
                            onClick={() => onMessage(item)}
                          />
                        )
                      }}
                    </Cell>
                    <Grid border={false} columnNum={3}>
                      <GridItem>
                        <p class={styles.title}>
                          {item.completeCourseNum || 0}/{item.totalCourseNum || 0}
                        </p>
                        <p class={styles.name}>课程</p>
                      </GridItem>
                      <GridItem>
                        <p class={[styles.title]}>
                          {item.completeTrainingNum || 0}/{item.totalTrainingNum || 0}
                        </p>
                        <p class={styles.name}>课后练习</p>
                      </GridItem>
                      <GridItem>
                        <p class={styles.title}>
                          {item.completeUnitTestNum || 0}/{item.totalUnitTestNum || 0}
                        </p>
                        <p class={styles.name}>单元测试</p>
                      </GridItem>
                    </Grid>
                  </CellGroup>
                ))}
            </div>
            <div class={styles.title}>
              <i></i>训练照片
            </div>
            {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) => (
                    <div class={styles.item} onClick={() => onDetail(item)}>
                      {item.coverUrl ? (
                        <Image class={styles.img} src={item.coverUrl} fit="cover" />
                      ) : (
                        <div class={[styles.img, styles.default]}>
                          <Image src={iconPhoneDefaut} class={styles.defaultImg} fit="cover" />
                        </div>
                      )}

                      <p class={[styles.name, 'van-ellipsis']}>{item.name}</p>
                      <p class={styles.num}>{item.photoCount}张</p>
                    </div>
                  ))}
                </div>
              </List>
            ) : (
              <OEmpty btnStatus={false} tips="暂无训练相片" />
            )}
          </>
        ) : (
          <OEmpty btnStatus={false} tips="暂无乐团" />
        )}

        <Popup v-model:show={state.orchestraStatus} position="bottom" round>
          <Picker
            columns={state.orchestraList}
            columnsFieldNames={{ text: 'orchestraName', value: 'orchestraId' }}
            onCancel={() => (state.orchestraStatus = false)}
            onConfirm={(val: any) => {
              const selectValue = val.selectedValues[0]
              if (selectValue === state.selectOrchestra.orchestraId) {
                state.orchestraStatus = false
                return
              }

              state.orchestraList.forEach((item: any) => {
                if (item.orchestraId === selectValue) {
                  state.selectOrchestra = item
                }
              })

              state.orchestraStatus = false
              onSearch()
            }}
          />
        </Popup>
      </div>
    )
  }
})
