<template>
  <Popup
    :show="popupShow"
    @close="onCancel"
    :closeIcon="false"
    position="bottom"
    closeable
  >
    <ActionSheetTitle 
      v-bind="titleProps"
      :title="title"
      @cancel="onCancel"
      @confirm="onConfirm"
    />
    <Picker 
      v-bind="props"
      v-model:value="tempValue"
      @selectTextChange="onSelectTextChange"
    />
  </Popup>
  <Text
    v-if="showSelectText"
    :size="30"
    :color="selectText && !(readonly || disabled) ? 'text.content' : 'text.second'"
    :text="selectText || placeholder" 
    :maxWidth="300"
    v-bind="textProps"
  />
</template>

<script setup lang="ts">
import { ref, toRef } from 'vue';
import { useFieldChildValueInjector } from './FormContext';
import { usePickerFieldTempStorageData } from './PickerUtils';
import type { PickerProps } from './Picker.vue';
import Popup from '../dialog/Popup.vue';
import ActionSheetTitle, { type ActionSheetTitleProps } from '../dialog/ActionSheetTitle.vue';
import Picker from './Picker.vue';
import Text, { type TextProps } from '../basic/Text.vue';
import { usePickerFieldInstance, type PickerFieldInstance } from './Picker';

export interface PickerFieldProps extends Omit<PickerProps, 'value'> {
  modelValue?: (number|string)[];
  /**
   * 标题
   */
  title?: string,
  /**
   * 标题属性
   */
  titleProps?: Omit<ActionSheetTitleProps, 'title'>,
  /**
   * 是否显示选中的文本
   */
  showSelectText?: boolean,
  /**
   * 占位符
   */
  placeholder?: string,
  /**
   * 初始值
   */
  initalValue?: (number|string)[];
  /**
   * 是否立即更新值
   */
  shouldUpdateValueImmediately?: boolean,
  /**
   * 显示的文本属性
   */
  textProps?: TextProps,
  /**
   * 是否禁用
   */
  disabled?: boolean,
  /**
   * 是否只读
   */
  readonly?: boolean,
}

const emit = defineEmits([ 'update:modelValue', 'cancel', 'confirm', 'selectTextChange', 'tempValueChange' ]);
const props = withDefaults(defineProps<PickerFieldProps>(), {
  modelValue: () => [],
  title: '请选择选项',
  placeholder: '请选择选项',
  titleProps: () => ({
    cancelText: '取消',
    confirmText: '确定',
  }),
  showSelectText: true,
  singleValue: false,
});

const popupShow = ref(false);

const {
  value,
  updateValue,
} = useFieldChildValueInjector(
  toRef(props, 'modelValue'), 
  (v) => emit('update:modelValue', v),
  undefined,
  () => {
    popupShow.value = true;
  },
  props.initalValue,
);

const {
  onSelectTextChange,
  onCancel,
  onConfirm,
  selectText,
  tempValue,
} = usePickerFieldTempStorageData(
  value,
  updateValue,
  () => popupShow.value = false,
  emit as any,
  [],
  props.shouldUpdateValueImmediately,
  undefined,
  popupShow,
);

defineExpose<PickerFieldInstance>(usePickerFieldInstance(popupShow));

defineOptions({
  options: {
    styleIsolation: "shared",
    virtualHost: true,
  }
})
</script>