import OHeader from '@/components/o-header'
import OSearch from '@/components/o-search'
import {
  Cell,
  Icon,
  Popover,
  Image,
  Checkbox,
  CheckboxGroup,
  Button,
  Popup,
  Picker,
  List
} from 'vant'
import { defineComponent, onMounted, reactive, watch } from 'vue'
import styles from './student-list.module.less'
import checkboxCheck from '@/common/images/icon-checkbox-check.png'
import checkboxDefault from '@/common/images/icon-checkbox-default.png'
import iconStudent from '@/common/images/icon_student.png'
import OSticky from '@/components/o-sticky'
import { state as baseState } from '@/state'
import request from '@/helpers/request'
import OEmpty from '@/components/o-empty'

export const classStr = {
  1: '一年级',
  2: '二年级',
  3: '三年级',
  4: '四年级',
  5: '五年级',
  6: '六年级',
  7: '七年级',
  8: '八年级',
  9: '九年级'
}

export default defineComponent({
  name: 'student-list',
  props: {
    orchestraList: {
      // 乐团列表
      type: Array,
      default: () => []
    },
    subjectId: {
      // 声部编号
      type: [String, Number],
      default: ''
    },
    selectStudentIds: {
      // 选中的学员列表
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'select'],
  setup(props, { slots, attrs, emit }) {
    const state = reactive({
      showPopover: false,
      oPopover: false,
      isLoad: false,
      classList: [
        { text: '全部', value: -1 },
        { text: '一年级', value: 1 },
        { text: '二年级', value: 2 },
        { text: '三年级', value: 3 },
        { text: '四年级', value: 4 },
        { text: '五年级', value: 5 },
        { text: '六年级', value: 6 },
        { text: '七年级', value: 7 },
        { text: '八年级', value: 8 },
        { text: '九年级', value: 9 }
      ] as any, // 年级列表
      check: [] as any,
      checkboxRefs: [] as any,
      orchestra: {
        id: null,
        name: '全部乐团'
      } as any,
      class: {
        id: null,
        name: '全部'
      } as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        keyword: null,
        page: 1,
        rows: 20
      }
    })

    const onSelect = (type: string) => {
      // console.log(state.checkboxRefs[type])
      state.checkboxRefs[type].toggle()
    }

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

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

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

    const onSubmit = () => {
      emit('close')
      emit('select', state.check)
      setTimeout(() => {
        state.check = []
      }, 100)
    }

    // 监听声部是否变化
    watch(
      () => props.subjectId,
      () => {
        console.log('subjectId')
        onSearch()
      }
    )

    // 监听选择学员变化
    watch(
      () => props.selectStudentIds,
      () => {
        console.log(props.selectStudentIds, 'watch')
        state.check = [...props.selectStudentIds]
      }
    )

    onMounted(() => {
      console.log(props.selectStudentIds, 'onmount')
      // 判断年级
      // if (baseState.user.data.school?.schoolSystem === 'sixYearSystem') {
      //   state.classList.push(
      //     ...[
      //       { text: '六年级', value: 6 },
      //       { text: '初一', value: 7 },
      //       { text: '初二', value: 8 },
      //       { text: '初三', value: 9 }
      //     ]
      //   )
      // } else {
      //   state.classList.push(
      //     ...[
      //       { text: '初一', value: 6 },
      //       { text: '初二', value: 7 },
      //       { text: '初三', value: 8 },
      //       { text: '初四', value: 9 }
      //     ]
      //   )
      // }

      if (props.orchestraList.length > 0) {
        const o: any = props.orchestraList[0]
        state.orchestra.id = o.value
        state.orchestra.name = o.text
      }

      // 获取学员列表
      getList()

      state.check = [...props.selectStudentIds]
    })

    return () => (
      <div class={styles.studentList}>
        <OSticky position="top">
          <OHeader title="选择学员" desotry={false} border={false} />
          <OSearch
            // inputBackground="white"
            // background="#F8F8F8"
            class="searchGroupInput"
            placeholder="学员名称/手机号"
            onSearch={(val: any) => {
              state.params.keyword = val
              onSearch()
            }}
          />
          <div class={'searchGroup'}>
            <div
              class={['searchItem searchItem-large', state.showPopover ? 'searchItem-active' : '']}
              onClick={() => (state.showPopover = true)}
            >
              <span>{state.class.name}</span>
              <i class="arrow"></i>
            </div>
            <div
              class={['searchItem searchItem-large', state.oPopover ? 'searchItem-active' : '']}
              onClick={() => (state.oPopover = true)}
            >
              <span>{state.orchestra.name}</span>
              <i class="arrow"></i>
            </div>
          </div>
        </OSticky>

        {state.listState.dataShow ? (
          <List
            // v-model:loading={state.listState.loading}
            finished={state.listState.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            style={{ paddingTop: '12px' }}
            immediateCheck={false}
          >
            <CheckboxGroup v-model={state.check}>
              {state.list.map((item: any) => (
                <Cell v-model={state.check} center onClick={() => onSelect(item.id)}>
                  {{
                    icon: () => <Image class={styles.img} src={item.avatar || iconStudent} />,
                    title: () => (
                      <div class={styles.content}>
                        <p class={styles.name}>{item.nickname}</p>
                        <p class={styles.class}>
                          {item.currentGradeNum > 0 ? classStr[item.currentGradeNum] : ''}
                        </p>
                      </div>
                    ),
                    'right-icon': () => (
                      <Checkbox
                        name={item.id}
                        ref={(el: any) => (state.checkboxRefs[item.id] = el)}
                        onClick={(e: any) => {
                          e.stopPropagation()
                          e.preventDefault()
                        }}
                        v-slots={{
                          icon: (props: any) => (
                            <Icon
                              class={styles.iconChecked}
                              name={props.checked ? checkboxCheck : checkboxDefault}
                            />
                          )
                        }}
                      />
                    )
                  }}
                </Cell>
              ))}
            </CheckboxGroup>
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无学员" />
        )}

        <OSticky position="bottom">
          <div class={['btnGroup', styles.btnMore]}>
            <Button
              type="primary"
              plain
              round
              style={{ backgroundColor: 'transparent' }}
              onClick={() => {
                state.list.forEach((item: any) => {
                  if (!state.check.includes(item.id)) {
                    state.check.push(item.id)
                  }
                })
                state.check
              }}
            >
              全选
            </Button>
            <Button type="primary" round block onClick={onSubmit}>
              确认
            </Button>
          </div>
        </OSticky>

        {/* 乐团 */}
        <Popup v-model:show={state.oPopover} position="bottom" round class={'popupBottomSearch'}>
          <Picker
            columns={props.orchestraList as any}
            onCancel={() => (state.oPopover = false)}
            onConfirm={(item: any) => {
              const selectedOptions = item.selectedOptions[0]
              state.orchestra.id = selectedOptions.value
              state.orchestra.name = selectedOptions.text

              state.oPopover = false
              onSearch()
            }}
          />
        </Popup>

        {/* 年级 */}
        <Popup v-model:show={state.showPopover} position="bottom" round class={'popupBottomSearch'}>
          <Picker
            columns={state.classList as any}
            onCancel={() => (state.showPopover = false)}
            onConfirm={(item: any) => {
              const selectedOptions = item.selectedOptions[0]
              state.class.id = selectedOptions.value
              state.class.name = selectedOptions.text

              state.showPopover = false
              onSearch()
            }}
          />
        </Popup>
      </div>
    )
  }
})
