import OHeader from '@/components/o-header'
import { Button, Checkbox, CheckboxGroup, Icon, Image } from 'vant'
import { defineComponent, onMounted, reactive, ref, watch } from 'vue'
import styles from './subject-list.module.less'
import checkboxCheck from '@/common/images/icon-checkbox-check.png'
import checkboxDefault from '@/common/images/icon-checkbox-default.png'
import OSticky from '@/components/o-sticky'

export default defineComponent({
  name: 'subject-list',
  props: {
    subjectList: {
      type: Array,
      default: () => []
    },
    selectSubjects: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'select'],
  setup(props, { slots, attrs, emit }) {
    const state = reactive({
      check: [] as any,
      checkboxRefs: [] as any
    })

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

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

    watch(
      () => props.selectSubjects,
      () => {
        state.check = [...props.selectSubjects]
      }
    )

    onMounted(() => {
      state.check = [...props.selectSubjects]
    })

    return () => (
      <div style={{ minHeight: '100vh' }}>
        <OHeader title="选择声部" />

        <CheckboxGroup
          class={styles.subjectList}
          v-model={state.check}
          style={{ paddingBottom: '24px' }}
        >
          {props.subjectList.map((item: any) => (
            <div class={styles.subject} onClick={() => onSelect(item.subjectId)}>
              <Checkbox
                name={item.subjectId}
                class={styles.checkbox}
                ref={(el: any) => (state.checkboxRefs[item.subjectId] = el)}
                onClick={(e: any) => {
                  e.stopPropagation()
                }}
                v-slots={{
                  icon: (props: any) => (
                    <Icon
                      class={styles.iconChecked}
                      name={props.checked ? checkboxCheck : checkboxDefault}
                    />
                  )
                }}
              />
              <Image class={styles.img} src={item.subjectImg} />
              <p class={styles.name}>{item.subjectName}</p>
            </div>
          ))}
        </CheckboxGroup>

        <OSticky position="bottom">
          <div class={['btnGroup', 'btnMore']} style="padding-left: 13px; padding-right: 13px;">
            <Button round color="#CCCCCC" onClick={() => emit('close')}>
              取消
            </Button>
            <Button type="primary" round onClick={onSubmit}>
              确认
            </Button>
          </div>
        </OSticky>
      </div>
    )
  }
})
