import { ActionSheet } from 'vant';
import { defineComponent, PropType, reactive, watch } from 'vue';
import styles from './index.module.less';

type actionsType = {
  name: string | number;
  value?: string | number;
  selected?: boolean;
};

export default defineComponent({
  name: 'k-action-sheet',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    actions: {
      type: Array as PropType<actionsType[]>,
      required: true,
      default: () => []
    },
    cancelText: {
      type: String,
      default: '取消'
    },
    teleport: {
      type: [String, Element],
      default: ''
    }
  },
  emits: ['update:show', 'select'],
  setup(props, { emit }) {
    const form = reactive({
      oPopover: props.show
    });

    const onSelect = (item: any) => {
      emit('select', item);
      emit('update:show', false);
    };

    watch(
      () => form.oPopover,
      () => {
        emit('update:show', form.oPopover);
      }
    );

    watch(
      () => props.show,
      () => {
        form.oPopover = props.show;
      }
    );

    return () => (
      <ActionSheet v-model:show={form.oPopover} teleport={props.teleport}>
        <div class={[styles['k-sheet_content'], 'van-hairline--bottom']}>
          {props.actions.map((item: any) => (
            <div
              class={[
                'van-sheet-item van-ellipsis',
                item.selected && 'van-sheet-item-active'
              ]}
              onClick={() => onSelect(item)}>
              {item.name}
            </div>
          ))}
        </div>

        <button
          type="button"
          class={[
            'van-action-sheet__cancel',
            styles['k-action-sheet_bottom__cancel']
          ]}
          onClick={() => emit('update:show', false)}>
          {props.cancelText}
        </button>
      </ActionSheet>
    );
  }
});
