import OHeader from '@/components/o-header'
import OPopup from '@/components/o-popup'
import OSticky from '@/components/o-sticky'
import { state } from '@/state'
import { Button, Cell, CellGroup, Field, List, Image, Tag } from 'vant'
import { defineComponent, onMounted, PropType, reactive, watch } from 'vue'
import TeacherList from '../modal/teacher-list'
import styles from './teacher-list.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: {
    header: {
      // 是否显示头部
      type: Boolean,
      default: true
    },
    mode: {
      type: String as PropType<'fixed' | 'sticky'>,
      default: 'fixed'
    },
    subjectId: {
      type: String,
      default: ''
    }
  },
  emits: ['close', 'select'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      teacherStatus: false,
      isLoad: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        keyword: null,
        subjectId: props.subjectId,
        page: 1,
        rows: 20
      }
    })

    const getList = async () => {
      try {
        if (forms.isLoad) return
        forms.isLoad = true
        const res = await request.post('/api-school/teacher/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.subjectName ? item.subjectName.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 = (item: any) => {
      emit('close')
      emit('select', item)
    }

    // 声部变化时重新请求接口
    watch(
      () => props.subjectId,
      () => {
        forms.params.subjectId = props.subjectId
        onSearch()
      }
    )

    onMounted(() => {
      getList()
    })

    return () => (
      <div>
        <OSticky position="top" mode={props.mode}>
          {props.header && <OHeader title="选择老师" />}
          <OSearch
            inputBackground="white"
            background="#F8F8F8"
            placeholder="老师名称/手机号"
            onSearch={(val: any) => {
              forms.params.keyword = val
              onSearch()
            }}
          />
        </OSticky>

        {forms.listState.dataShow ? (
          <List
            v-model:loading={forms.listState.loading}
            finished={forms.listState.finished}
            finishedText=" "
            onLoad={getList}
            immediateCheck={false}
          >
            {forms.list.map((item: any) => (
              <Cell center class={styles.cellTeacher} onClick={() => onSelect(item)}>
                {{
                  icon: () => <Image class={styles.img} src={item.avatar || iconTeacher} />,
                  title: () => (
                    <div class={styles.content}>
                      <p class={styles.name}>{item.nickname}</p>
                      <p class={styles.class}>
                        {item.subjectNames &&
                          item.subjectNames.map((subject: any) => (
                            <Tag type="primary">{subject}</Tag>
                          ))}
                      </p>
                    </div>
                  )
                }}
              </Cell>
            ))}
          </List>
        ) : (
          <OEmpty btnStatus={false} classImgSize="SMALL" tips="暂无老师" />
        )}
      </div>
    )
  }
})
