import { state } from '@/state'
import {
  Button,
  Cell,
  CellGroup,
  Field,
  List,
  Image,
  Tag,
  Sticky,
  Checkbox,
  CheckboxGroup
} from 'vant'
import { defineComponent, onMounted, PropType, reactive, watch } from 'vue'
import styles from './index.module.less'
import iconTeacher from '@common/images/icon_teacher.png'
import OEmpty from '@/components/o-empty'
import request from '@/helpers/request'
import OSearch from '@/components/o-search'

export default defineComponent({
  name: 'teacher-list',
  props: {
    height: {
      type: [String, Number],
      default: 'auto'
    },
    bottomHeight: {
      type: [String, Number],
      default: 0
    },
    selectItem: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'select', 'update:selectItem'],
  setup(props, { emit }) {
    const forms = reactive({
      teacherStatus: false,
      isLoad: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        keyword: null,
        page: 1,
        rows: 20
      },
      check: (props.selectItem || []) as any,
      checkboxRefs: [] as any
    })

    const getList = async () => {
      try {
        if (forms.isLoad) return
        forms.isLoad = true
        const res = await request.post('/api-school/student/page', {
          data: {
            ...forms.params,
            schoolId: state.user.data.school.id
          }
        })
        forms.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (forms.list.length > 0 && result.current === 1) {
          return
        }
        const rows = result.rows || []
        rows.forEach((item: any) => {
          item.subjectNames = item.subjectNames ? item.subjectNames.split(',') : []
        })
        forms.list = forms.list.concat(rows)
        forms.listState.finished = result.current >= result.pages
        forms.params.page = result.current + 1
        forms.listState.dataShow = forms.list.length > 0

        forms.isLoad = false
      } catch {
        forms.listState.dataShow = false
        forms.listState.finished = true
        forms.isLoad = false
      }
    }

    // 搜索
    const onSearch = () => {
      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 list: any = []
      forms.list.forEach((item: any) => {
        if (forms.check.includes(item.id)) {
          list.push({
            id: item.id,
            value: item.nickname,
            avatar: item.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(() => {
      getList()
      initSelectItem()
    })

    return () => (
      <div
        class={[!forms.listState.dataShow && 'emptyRootContainer']}
        style={{ 'min-height': `calc(100vh - ${props.height}px - ${props.bottomHeight}px)` }}
      >
        <Sticky position="top" offsetTop={props.height} style={{ width: '100%' }}>
          <OSearch
            // inputBackground="white"
            // background="#F8F8F8"
            placeholder="学员名称/手机号"
            onSearch={(val: any) => {
              forms.params.keyword = val
              onSearch()
            }}
          />
        </Sticky>

        {forms.listState.dataShow ? (
          <List
            // v-model:loading={forms.listState.loading}
            finished={forms.listState.finished}
            finishedText=" "
            onLoad={getList}
            style={{
              paddingTop: '12px'
            }}
            immediateCheck={false}
          >
            <CheckboxGroup class={[styles.gridContainer, styles.gridClass]} v-model={forms.check}>
              {forms.list.map((item: any) => (
                <CellGroup inset style={{ marginBottom: '12px' }} onClick={() => onSelect(item.id)}>
                  <Cell center class={styles.cellTeacher} valueClass={styles.checkboxValue}>
                    {{
                      icon: () => (
                        <Image class={styles.img} src={item.avatar || iconTeacher} fit="cover" />
                      ),
                      title: () => (
                        <div class={styles.content}>
                          <p class={[styles.name, 'van-ellipsis']}>{item.nickname}</p>
                          <p class={styles.class}>
                            {item.subjectNames &&
                              item.subjectNames.map((subject: any) => (
                                <Tag
                                  type="primary"
                                  class={styles.tagSubject}
                                  color="#FFE7DA"
                                  textColor="#F67146"
                                >
                                  {subject}
                                </Tag>
                              ))}
                          </p>
                        </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>
                </CellGroup>
              ))}
            </CheckboxGroup>
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无学生" />
        )}
      </div>
    )
  }
})
