import { Button, Picker, PickerColumn } from 'vant';
import {
  PropType,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';

export default defineComponent({
  name: 'drop-down-modal',
  props: {
    selectValues: {
      type: [String, Number],
      default: null
    },
    columns: {
      type: Array as PropType<PickerColumn>,
      default: () => []
    },
    open: {
      type: Boolean,
      default: false
    }
  },
  emits: ['dropDownClose', 'dropDownConfirm'],
  setup(props, { emit }) {
    const forms = reactive({
      values: [] as any
    });
    const pickerRef = ref();

    onMounted(() => {
      forms.values = [props.selectValues];
    });

    watch(
      () => props.selectValues,
      () => {
        forms.values = [props.selectValues];
      }
    );
    watch(
      () => props.open,
      () => {
        setTimeout(() => {
          forms.values = [props.selectValues];
        }, 100);
      }
    );
    return () => (
      <>
        <Picker
          ref={pickerRef}
          v-model={forms.values}
          showToolbar={false}
          visibleOptionNum={5}
          columns={props.columns}
          onConfirm={() => {
            emit('dropDownConfirm', forms.values);
          }}
        />
        <div class={['btnGroupPopup', 'van-hairline--top']}>
          <Button round onClick={() => emit('dropDownClose')}>
            取消
          </Button>
          <Button
            type="primary"
            round
            onClick={async () => {
              await pickerRef.value.confirm();
            }}>
            确定
          </Button>
        </div>
      </>
    );
  }
});
