import OHeader from '@/components/o-header'
import OSearch from '@/components/o-search'
import OSticky from '@/components/o-sticky'
import { Cell, Icon, Image, List } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import iconTeacher from '@common/images/icon_teacher.png'
import { useRouter } from 'vue-router'
import request from '@/helpers/request'
import { state } from '@/state'
import OEmpty from '@/components/o-empty'
import OFullRefresh from '@/components/o-full-refresh'
import { manageTeacherType } from '@/constant'
import OActionSheet from '@/components/o-action-sheet'

export default defineComponent({
  name: 'companion-teacher',
  setup() {
    const router = useRouter()
    const form = reactive({
      oPopover: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      statusText: '状态',
      params: {
        keyword: null,
        status: null,
        page: 1,
        rows: 20
      },
      isClick: false,
      actions: [
        { name: '全部', id: 'ALL', selected: true },
        // { name: '注销', id: 'CANCEL' },
        { name: '冻结', id: 'LOCKED' },
        { name: '正常', id: 'ACTIVATION' }
      ]
    })

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

    const onSearch = () => {
      form.params.page = 1
      form.list = []
      form.listState.dataShow = true // 判断是否有数据
      form.listState.loading = false
      form.listState.finished = false
      getList()
    }

    const onDetail = (item: any) => {
      router.push({
        path: '/manage-teacher-detail',
        query: {
          id: item.id
        }
      })
    }

    onMounted(async () => {
      getList()
    })
    return () => (
      <div class={!form.listState.dataShow && 'emptyRootContainer'}>
        <OSticky
          position="top"
          onGetHeight={(height: any) => {
            form.listState.height = height
          }}
        >
          <OHeader border={false}>
            {{
              right: () => (
                <Icon
                  name="plus"
                  size={19}
                  onClick={() => {
                    router.push({
                      path: 'save-share-image',
                      query: {
                        type: 'manage'
                      }
                    })
                  }}
                />
              )
            }}
          </OHeader>
          <OSearch
            placeholder="请输入管理老师姓名"
            // inputBackground="white"
            // background="#f6f8f9"
            onSearch={(val: any) => {
              console.log(val)
              form.params.keyword = val
              onSearch()
            }}
            v-slots={{
              left: () => (
                <div
                  class={['searchItem-left', form.oPopover ? 'searchItem-active' : '']}
                  onClick={() => (form.oPopover = true)}
                >
                  <span>{form.statusText}</span>
                </div>
              )
            }}
          />
        </OSticky>
        {form.listState.dataShow ? (
          <OFullRefresh
            v-model:modelValue={form.listState.refreshing}
            onRefresh={onSearch}
            style={{
              minHeight: `calc(100vh - ${form.listState.height}px)`
            }}
          >
            <List
              // v-model:loading={form.listState.loading}
              finished={form.listState.finished}
              finishedText=" "
              class={[styles.liveList]}
              onLoad={getList}
              style={{ paddingTop: '12px' }}
              immediateCheck={false}
            >
              {form.list.map((item: any) => (
                <Cell center isLink class={styles.manageCell} onClick={() => onDetail(item)}>
                  {{
                    icon: () => (
                      <Image class={styles.img} src={item.avatar ? item.avatar : iconTeacher} />
                    ),
                    title: () => (
                      <div class={styles.content}>
                        <p class={[styles.name, 'van-ellipsis']}>{item.nickname}</p>
                        <p class={styles.phone}>{item.phone}</p>
                      </div>
                    ),
                    value: () => (
                      <span class={[styles.status, item.status === 'LOCKED' ? styles.frozen : '']}>
                        {manageTeacherType[item.status]}
                      </span>
                    )
                  }}
                </Cell>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty btnStatus={false} tips="暂无管理老师" />
        )}

        <OActionSheet
          v-model:show={form.oPopover}
          actions={form.actions}
          onSelect={(val: any) => {
            form.actions.forEach((child: any) => {
              child.selected = false
            })
            val.selected = true
            form.statusText = val.name
            form.params.status = val.id === 'ALL' ? null : val.id
            form.oPopover = false
            onSearch()
          }}
        />
      </div>
    )
  }
})
