<script setup lang="ts">
import type { CascaderOption } from '@/request/model';
import type { DialogProps, PickerInstance } from 'vant';

type Selected = Omit<CascaderOption, 'children'>;

export interface Props {
  options: CascaderOption[];
  selected?: string[];
  loading?: boolean;
  title?: string;
  /* 点击最后选项直接确定 */
  immediate?: boolean;
}

const props = defineProps<Props>();
const emits = defineEmits<{ closed: []; selected: [Selected[]] }>();
const show = defineModel('show', { default: false });

const dialog = reactive<Partial<DialogProps>>({
  showCancelButton: true,
});

watchEffect(() => {
  dialog.title = props.title ?? void 0;
  dialog.showConfirmButton = !props.immediate;
});

const picker = useTemplateRef<PickerInstance>('picker');
const dialogConfirmHandle = (emit?: boolean) => {
  const options = picker.value?.getSelectedOptions() ?? [];
  if (emit)
    emits(
      'selected',
      options.map((option) => ({ label: option?.label, value: option?.value }) as Selected)
    );
  show.value = false;
};
const dialogCancelHandle = () => {
  show.value = false;
};
const dialogOpenHandle = () => {
  show.value = true;
};
const dialogClosedHandle = () => {
  emits('closed');
};
</script>

<template>
  <div>
    <slot :handle="dialogOpenHandle"></slot>
    <van-dialog
      class="sub-dialog scrollable"
      :show="show"
      v-bind="dialog"
      :confirm-button-disabled="loading"
      @confirm="dialogConfirmHandle(true)"
      @cancel="dialogCancelHandle"
      @open="dialogOpenHandle"
      @closed="dialogClosedHandle"
    >
      <van-picker
        ref="picker"
        :loading="props.loading"
        :modelValue="selected"
        :show-toolbar="false"
        :visible-option-num="10"
        :columns="props.options"
        :columns-field-names="{ text: 'label', value: 'value', children: 'children' }"
      ></van-picker>
    </van-dialog>
  </div>
</template>

<style scoped lang="scss">
.form-wrapper {
  .van-field {
    margin: 0;
    padding: 0;
  }

  :deep(.van-field__control) {
    margin-bottom: 24px;
    padding: 8px;
    border: 1px solid #38ff6e;
    border-radius: 8px;
    text-align: center;
  }
}

.sub-option.checked {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
<style lang="scss">
.sub-dialog {
  --van-dialog-width: 60vw;
  --van-dialog-font-size: 24px;
  --van-dialog-button-height: 60px;
  --van-button-default-font-size: 24px;

  &.scrollable {
    max-height: 80vh;
    display: flex;
    flex-direction: column;

    .van-dialog__header {
      padding-bottom: var(--van-dialog-header-padding-top);
    }

    .van-dialog__content {
      flex: auto;
      overflow-y: auto;
    }
  }
}
</style>
