import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
import {
  Button,
  Cell,
  CellGroup,
  Checkbox,
  CheckboxGroup,
  Grid,
  GridItem,
  Icon,
  Image,
  List,
  Picker,
  Popup,
  Tag
} from 'vant'
import { defineComponent, onMounted, reactive, watch } from 'vue'
import styles from './index.module.less'
import iconTeacher from '@common/images/icon_teacher.png'
import { state as baseState } from '@/state'
import request from '@/helpers/request'
import OEmpty from '@/components/o-empty'

export default defineComponent({
  name: 'practice-class',
  props: {
    classType: {
      type: String,
      default: ''
    },
    orchestraId: {
      // 乐团编号
      type: String,
      default: ''
    },
    selectItem: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      showPopover: false,
      orchestraId: (props.orchestraId || null) as any,
      orchestraName: null as any,
      orchestraList: [] as any,
      isClick: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      },
      check: (props.selectItem || []) as any,
      checkboxRefs: [] as any
    })
    // 获取乐团列表
    const getOrchestras = async () => {
      try {
        const { data } = await request.post('/api-school/orchestra/page', {
          data: {
            page: 1,
            rows: 100,
            schoolId: baseState.user.data.school.id
          }
        })
        const temps = data.rows || []
        const s = [] as any
        temps.forEach((item: any) => {
          s.push({
            text: item.name,
            value: item.id
          })
        })
        forms.orchestraList = [...s]

        // 判断是否有乐团
        if (s.length > 0) {
          forms.orchestraId = s[0].value
          forms.orchestraName = s[0].text
        }
      } catch {
        //
      }
    }

    // 获取班级
    const getList = async () => {
      // 查询没有设置指导老师的班级
      try {
        if (forms.isClick) return
        forms.isClick = true
        const { data } = await request.post('/api-school/classGroup/page', {
          data: {
            ...forms.params,
            schoolId: baseState.user.data.school.id,
            orchestraId: forms.orchestraId,
            classType: props.classType
            // orchestraType: 'DELIVERY'
          }
        })
        forms.isClick = false
        // 班级数据
        forms.listState.loading = false
        const result = data || {}
        // 处理重复请求数据
        if (forms.list.length > 0 && result.current === 1) {
          return
        }
        forms.list = forms.list.concat(result.rows || [])
        forms.listState.finished = result.current >= result.pages
        forms.params.page = result.current + 1
        forms.listState.dataShow = forms.list.length > 0
      } catch {
        forms.listState.dataShow = false
        forms.listState.finished = true
        forms.isClick = false
      }
    }

    // 监听班级类型变化
    watch(
      () => props.classType,
      () => {
        forms.params.page = 1
        forms.list = []
        forms.listState.dataShow = true // 判断是否有数据
        forms.listState.loading = false
        forms.listState.finished = false
        getList()
      }
    )

    const onSelect = (type: string) => {
      forms.checkboxRefs[type].toggle()
    }

    // 确定选择班级
    const onSubmit = () => {
      emit('confirm', forms.check)
      emit('close')
    }

    onMounted(async () => {
      // 判断是否有乐团编号
      if (!props.orchestraId) {
        await getOrchestras()
      }
      await getList()
    })

    return () => (
      <div class={styles.practiceClass}>
        <OSticky position="top">
          <OHeader title="选择班级" desotry={false} />
          {!props.orchestraId && (
            <div style={{ padding: '12px 13px', background: '#f6f6f6' }}>
              <div class={styles.searchBand} onClick={() => (forms.showPopover = true)}>
                <div class={['van-ellipsis', styles.bandName]}>{forms.orchestraName}</div>
                <Icon name={forms.showPopover ? 'arrow-up' : 'arrow-down'} />
              </div>
            </div>
          )}
        </OSticky>

        {forms.listState.dataShow ? (
          <List
            v-model:loading={forms.listState.loading}
            finished={forms.listState.finished}
            style={{ marginTop: props.orchestraId ? '12px' : 0 }}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            immediateCheck={false}
          >
            <CheckboxGroup class={[styles.gridContainer, styles.gridClass]} v-model={forms.check}>
              {forms.list.map((item: any) => (
                <CellGroup
                  class={styles.classCellGroup}
                  onClick={() => {
                    if (item.teacherId) {
                      onSelect(item.id)
                    }
                  }}
                  border={false}
                >
                  <Cell center titleStyle={{ flex: '0 auto' }} valueClass={styles.classCheckbox}>
                    {{
                      icon: () => <Image src={iconTeacher} class={styles.img} />,
                      title: () => (
                        <div class={styles.content}>
                          <div class={styles.teacherName}>
                            {item.teacherName ? (
                              <div class={[styles.name, styles.maxWidth, 'van-ellipsis']}>
                                {item.teacherName}
                              </div>
                            ) : (
                              <div class={[styles.name, 'van-ellipsis']} style={{ color: 'red' }}>
                                暂未设置伴学指导
                              </div>
                            )}
                            <Tag type="primary">{item.name}</Tag>
                          </div>
                          <div class={[styles.orchestraName, 'van-ellipsis']}>
                            {item.orchestraName}
                          </div>
                        </div>
                      ),
                      value: () => (
                        <Checkbox
                          name={item.id}
                          ref={(el: any) => (forms.checkboxRefs[item.id] = el)}
                          disabled={item.teacherId ? false : true}
                          onClick={(e: any) => {
                            e.stopPropagation()
                          }}
                        ></Checkbox>
                      )
                    }}
                  </Cell>
                  <Grid border={false} columnNum={3}>
                    <GridItem>
                      <p class={styles.title}>{item.preStudentNum}</p>
                      <p class={styles.name}>学生人数</p>
                    </GridItem>
                    <GridItem>
                      <p class={[styles.title]}>
                        {item.courseScheduleNum - item.completeCourseScheduleNum}
                      </p>
                      <p class={styles.name}>剩余课时</p>
                    </GridItem>
                    <GridItem>
                      <p class={styles.title}>{item.courseScheduleNum}</p>
                      <p class={styles.name}>总课时</p>
                    </GridItem>
                  </Grid>
                </CellGroup>
              ))}
            </CheckboxGroup>
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无班级" />
        )}

        <OSticky position="bottom">
          <div class={'btnGroup'}>
            <Button block round type="primary" onClick={onSubmit}>
              确认
            </Button>
          </div>
        </OSticky>

        <Popup v-model:show={forms.showPopover} position="bottom" round>
          <Picker
            columns={forms.orchestraList}
            onCancel={() => (forms.showPopover = false)}
            onConfirm={(val: any) => {
              forms.orchestraId = val.selectedOptions[0].value
              forms.orchestraName = val.selectedOptions[0].text
              forms.showPopover = false

              forms.params.page = 1
              forms.list = []
              forms.listState.dataShow = true // 判断是否有数据
              forms.listState.loading = false
              forms.listState.finished = false
              getList()
            }}
          />
        </Popup>
      </div>
    )
  }
})
