import { ref, watch, defineComponent } from 'vue';
import {
  getDatePickerProps,
  getEditorEmits,
  useNamespace,
} from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-date-picker/ibiz-date-picker.scss';
import dayjs from 'dayjs';

export const IBizDatePicker = defineComponent({
  name: 'IBizDatePicker',
  props: getDatePickerProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('date-picker');
    const c = props.controller;

    const editorModel = c!.model;

    const type = ref('date');
    const format = ref('yyyy-MM-dd');

    switch (editorModel.editorType) {
      case 'DATEPICKEREX':
      case 'DATEPICKEREX_NOTIME':
        type.value = 'date';
        break;
      case 'DATEPICKEREX_HOUR':
      case 'DATEPICKEREX_MINUTE':
      case 'DATEPICKEREX_SECOND':
      case 'DATEPICKEREX_NODAY':
      case 'DATEPICKEREX_NODAY_NOSECOND':
      case 'DATEPICKEREX_NOSECOND':
      case 'DATEPICKER':
      default:
        type.value = 'datetime';
    }
    // 值格式化
    const valueFormat = c!.valueFormat;
    if (valueFormat) {
      const tempFormat: string = valueFormat
        .replace('YYYY', 'yyyy')
        .replace('DD', 'dd');
      format.value = tempFormat;
    }
    const formatValue = ref();
    watch(
      () => props.value,
      (newVal, oldVal) => {
        // 空值不转换
        if (newVal && newVal !== oldVal) {
          formatValue.value = dayjs(newVal).format(valueFormat);
        }
      },
      { immediate: true },
    );
    // 处理值变更
    const handleChange = (date: string, _dateType: IData) => {
      emit('change', date);
    };

    const onOpenChange = (isOpen: boolean) => {
      emit('operate', isOpen);
    };

    const inputRef = ref();

    if (props.autoFocus) {
      watch(inputRef, newVal => {
        if (newVal) {
          const input = newVal.$el.getElementsByTagName('input')[0];
          input.click();
        }
      });
    }

    return {
      ns,
      c,
      editorModel,
      type,
      format,
      formatValue,
      handleChange,
      onOpenChange,
      inputRef,
    };
  },
  render() {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {this.readonly ? (
          this.formatValue
        ) : (
          <i-CalendarPicker
            ref='inputRef'
            transfer
            type={this.type}
            format={this.format}
            placeholder={this.c!.placeHolder}
            value={this.value}
            on-on-open-change={this.onOpenChange}
            on-on-change={this.handleChange}
            disabled={this.disabled}
          ></i-CalendarPicker>
        )}
      </div>
    );
  },
});
