import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
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 './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: {
    height: {
      type: [String, Number],
      default: 'auto'
    },
    bottomHeight: {
      type: [String, Number],
      default: 0
    },
    headerHeight: {
      type: [String, Number],
      default: 0
    },
    removeTeacherId: {
      type: String,
      default: ''
    },
    subjectIdList: {
      type: Array,
      default: () => []
    },
    selectItem: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'select', 'update:selectItem'],
  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,
        subjectIdList: props.subjectIdList,
        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/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 = (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.headerHeight} 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=" "
            style={{
              paddingTop: '12px'
            }}
            onLoad={getList}
            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>
                        </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>
                  <Cell center>
                    {{
                      title: () => (
                        <div class={styles.subjectContainer}>
                          <span>声部：</span>
                          <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap' }}>
                            {item.subjectNames &&
                              item.subjectNames.map((subject: any) => (
                                <Tag
                                  type="primary"
                                  class={styles.tagSubject}
                                  color="#FFE7DA"
                                  textColor="#F67146"
                                >
                                  {subject}
                                </Tag>
                              ))}
                          </div>
                        </div>
                      )
                    }}
                  </Cell>
                </CellGroup>
              ))}
            </CheckboxGroup>
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无伴学老师" />
        )}
      </div>
    )
  }
})
