import OHeader from '@/components/o-header'
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 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'
    },
    courseType: {
      type: String,
      default: ''
    },
    removeTeacherId: {
      type: String,
      default: ''
    },
    subjectIdList: {
      type: Array,
      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,
        courseType: props.courseType,
        subjectIdList: props.subjectIdList,
        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,
            removeTeacherId: props.removeTeacherId, // 移除的老师id
            delFlag: false // 绑定解绑 false:绑定 true:解绑
          }
        })
        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.courseType,
      () => {
        forms.params.courseType = props.courseType
        onSearch()
      }
    )
    watch(
      () => props.subjectIdList,
      () => {
        forms.params.subjectIdList = props.subjectIdList
        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, 'van-ellipsis']}>{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} tips="暂无老师" />
        )}
      </div>
    )
  }
})
