import { Ref, defineComponent, ref, watch } from 'vue'
import { Tag, CheckboxGroup, Checkbox, RadioGroup, Radio, Button } from 'vant'
import styles from './index.module.less'
import classNames from 'classnames'

export default defineComponent({
  name: 'SelectTagChild',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    child: {
      type: Array,
      default: () => []
    },
    choiceSubjectIds: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { attrs, emit }) {
    const subjects: Ref<Array<any | number>> = ref([...props.choiceSubjectIds])

    const onSelect = val => {
      setTimeout(() => {
        val.forEach(i => {
          if (!subjects.value.includes(i)) {
            subjects.value.push(i)
          }
        })
      }, 100)
    }

    watch(
      () => props.show,
      () => {
        if (!props.show) {
          resetTags()
        } else {
          subjects.value = [...props.choiceSubjectIds]
        }
      }
    )

    const resetTags = () => {
      console.log(props.choiceSubjectIds)
      subjects.value = [...props.choiceSubjectIds]
      emit('close')
    }
    return () => {
      return (
        <div class={styles.select}>
          <h4 class={styles.title}>全部声部</h4>
          <div class={styles.content}>
            <CheckboxGroup
              class={classNames(styles.childContent, styles['radio-group'])}
              modelValue={subjects.value}
              onUpdate:modelValue={val => {
                onSelect!(val)
              }}
            >
              {props.child.map((item: any) => (
                <Checkbox
                  key={item.id}
                  name={item.id}
                  class={styles.radio}
                  onClick={() => {
                    onSelect!([item.id])
                  }}
                >
                  <Tag
                    class={classNames(styles.item, 'van-ellipsis')}
                    plain={!subjects.value.includes(item.id)}
                    type="primary"
                    round
                    size="large"
                  >
                    {item.name}
                  </Tag>
                </Checkbox>
              ))}
            </CheckboxGroup>
          </div>
          <footer class="van-safe-area-bottom van-hairline--top">
            <Button class={styles.btn} round onClick={resetTags}>
              重置
            </Button>
            <Button
              class={styles.btn}
              type="primary"
              round
              onClick={() => emit('confirm', subjects.value)}
            >
              确认
            </Button>
          </footer>
        </div>
      )
    }
  }
})
