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,
  Sticky,
  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: {
    height: {
      type: [String, Number],
      default: 'auto'
    },
    selectItem: {
      type: Array,
      default: []
    }
  },
  emits: ['close', 'confirm', 'update:selectItem'],
  setup(props, { emit }) {
    const forms = reactive({
      showPopover: false,
      orchestraId: null as any,
      orchestraName: null as any,
      orchestraList: [] as any,
      isClick: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        type: null,
        page: 1,
        rows: 20
      },
      check: [] 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
          }
        })
        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
      }
    }

    const onSelect = (type: string) => {
      console.log(type, '2121')
      forms.checkboxRefs[type].toggle()

      const list: any = []
      forms.list.forEach((item: any) => {
        if (forms.check.includes(item.id)) {
          list.push({
            id: item.id,
            value: item.name,
            avatar: ''
          })
        }
      })
      emit('update:selectItem', list)
    }

    watch(
      () => props.selectItem,
      () => {
        initSelectItem()
      },
      { deep: true }
    )

    const initSelectItem = () => {
      const selectItem = props.selectItem || []
      const temp: any = []
      selectItem.forEach((item: any) => {
        temp.push(item.id)
      })
      forms.check = temp
    }
    onMounted(async () => {
      await getOrchestras()
      await getList()
      initSelectItem()
    })

    return () => (
      <div class={styles.practiceClass}>
        <Sticky position="top" offsetTop={props.height}>
          <div style={{ padding: '12px 13px', background: '#f6f6f6' }}>
            <div class={styles.searchBand} onClick={() => (forms.showPopover = true)}>
              {forms.orchestraName} <Icon name={forms.showPopover ? 'arrow-up' : 'arrow-down'} />
            </div>
          </div>
        </Sticky>

        {forms.listState.dataShow ? (
          <List
            v-model:loading={forms.listState.loading}
            finished={forms.listState.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            immediateCheck={false}
          >
            <CheckboxGroup
              class={[styles.gridContainer, styles.gridClass]}
              v-model={forms.check}
              // onChange={(val: any) => {
              //   console.log(val, '1212')
              //   const list: any = []
              //   forms.list.forEach((item: any) => {
              //     if (val.includes(item.id)) {
              //       list.push({
              //         id: item.id,
              //         value: item.name,
              //         avatar: ''
              //       })
              //     }
              //   })
              //   emit('change', list)
              // }}
            >
              {forms.list.map((item: any) => (
                <CellGroup class={styles.classCellGroup} onClick={() => onSelect(item.id)}>
                  <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}>
                            <span class={['van-ellipsis', styles.name]}>{item.teacherName}</span>
                            <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)}
                          onClick={(e: any) => {
                            e.preventDefault()
                            e.stopPropagation()
                            onSelect(item.id)
                          }}
                        ></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="暂无班级" />
        )}

        <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>
    )
  }
})
